Search code examples
phpclassmethodsconstruct

PHP OOP constructing class property form method in same class


For some reason I can't get this to work:

<?php 
class Number{
    public $number;
    public $number_added;


    public function __construct(){
        $this->number_added = $this->add_two();
    }

    public function add_two(){
        return $this->number + 2;
    }
}   
?>

$this->number is set from Database, $this->number_two should be DB value + 2. However, when I echo $this->number_added, it returns two. The $number value was initialized correctly. This is a simplified example of my problem just to see if what I am trying to do possible? PHP OOP beginner.


Solution

  • You aren't setting the $number property anywhere prior to its use in add_two() (via the constructor), therefore PHP evaluates it as 0 during the addition.

    You should pass in initial state during object construction, for example

    public function __construct($number) {
        $this->number = $number;
    
        $this->number_added = $this->add_two();
    }
    

    Update

    Allow me to illustrate the problem. Here's your current code and how I imagine you're using it

    $number = 2;
    
    $obj = new Number();
    // right here, $obj->number is null (0 in a numeric sense)
    // as your constructor calls add_two(), $obj->number_added is 2 (0 + 2)
    
    $obj->number = $number;
    // now $obj->number is 2 whilst $obj->number_added remains 2
    

    Using my updated constructor, here is what happens

    $number = 2;
    
    $obj = new Number($number);
    // $obj->number is set to $number (2) and a call to add_two() is made
    // therefore $obj->number_added is 4