php - Warning: Attempt to assign property of non-object, but the Object exists -
this class:
class network { protected $value = null; protected $properties = array(); public $type = null; function __construct($value = null, $type = null) { $this->value = $value; $this->type = $type; } public function __set($name, $value) { if(isset($this->{$name})) { $this->{$name} = $value; } else { $this->properties[$name] = new self($value, null); } } public function __get($name) { return $this->properties[$name]->value; } public function __tostring() { return $this->value; } }
this trying do:
$networks = new \stdclass(); $networks->test= new \orange_post\network('test'); $networks->test->enabled = true; $networks->test->enabled->type = 'boolean';
but error:
warning: attempt assign property of non-object on last line, $networks->test->enabled->type = 'boolean';
this first attempt @ branching out , doing this, , can't figure out doing incorrectly.
so going on here?
$networks = new \stdclass(); $networks->test= new \orange_post\network('test'); $networks->test->enabled = true; $networks->test->enabled->type = 'boolean'; ↑ ↑ ↑ ↑ tries access property of value ('true') | | | 'enabled' property never exists | | property instance of '\orange_post\network' | instance of '\stdclass'
first off, when try assign true
property enabled
. __set()
gets called, since property doesn't exists.
public function __set($name, $value) { if(isset($this->{$name})) { $this->{$name} = $value; } else { $this->properties[$name] = new self($value, null); } }
in magic method assign new instace of class property array properties
, use name (enabled
) index.
$networks->test->enabled->type = 'boolean';
after try set property type
property enabled
. here __get
gets invoked.
public function __get($name) { return $this->properties[$name]->value; }
so return array value of properties
, return property value
of it. , property value
not object. remove ->value
part , code return object.
in other words last line:
$networks->test->enabled->type = 'boolean';
becomes:
$networks->test->properties["enabled"]->value->type = 'boolean'; ↑ ↑ causing problem | holds object | holds 'true' property value
Comments
Post a Comment