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.
You aren’t setting the
$numberproperty anywhere prior to its use inadd_two()(via the constructor), therefore PHP evaluates it as0during the addition.You should pass in initial state during object construction, for example
Update
Allow me to illustrate the problem. Here’s your current code and how I imagine you’re using it
Using my updated constructor, here is what happens