need help in php class and object

Discussion in 'PHP' started by sunnyverma1984, Apr 8, 2010.

  1. #1
    i am getting error in following php code
    <?
    class sewatch {
    public $sum=$this->add();
    public function add()
    {
    return 5;
    }
    
    }
    $o=new sewatch();
    echo $o->sum;
    ?>
    PHP:
    Parse error: parse error in C:\wamp\www\mainclass.php on line 3
    Code (markup):

     
    sunnyverma1984, Apr 8, 2010 IP
  2. itmedia

    itmedia Peon

    Messages:
    43
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #2
    i would believe it needs ;
    here :)
     
    itmedia, Apr 8, 2010 IP
  3. lukeg32

    lukeg32 Peon

    Messages:
    645
    Likes Received:
    19
    Best Answers:
    1
    Trophy Points:
    0
    #3
    What are you trying to do exactly? The problem you have is here;

    public $sum=$this->add();
    PHP:
    Without understanding what you are trying to achieve, exactly, its hard to answer although this;

    <?
    class sewatch {
    
    public $sum = null;
    
    public function __construct()
    {
    $this->sum = $this->add();
    }
    
    public function add()
    {
    return 5;
    }
    }
    $o=new sewatch();
    echo $o->sum;
    ?>
    PHP:
    Will output "5" if that is all you need.
     
    lukeg32, Apr 8, 2010 IP
  4. nabil_kadimi

    nabil_kadimi Well-Known Member

    Messages:
    1,065
    Likes Received:
    69
    Best Answers:
    0
    Trophy Points:
    195
    #4
    The 3rd line is not valid, see this documentation page from PHP.net

    
    <?php
    class SimpleClass
    {
       // invalid property declarations:
       public $var1 = 'hello ' . 'world';
       public $var2 = <<<EOD
    hello world
    EOD;
       public $var3 = 1+2;
       public $var4 = self::myStaticMethod();
       public $var5 = $myVar;
    
       // valid property declarations:
       public $var6 = myConstant;
       public $var7 = array(true, false);
    
       // This is allowed only in PHP 5.3.0 and later.
       public $var8 = <<<'EOD'
    hello world
    EOD;
    }
    ?>
    
    PHP:
    As suggested by lukeg32, you should declare the property then set it's value inside the constructor method __construct()
     
    nabil_kadimi, Apr 8, 2010 IP