|
Posted by Jon Maz on 10/13/37 11:31
Hi All,
I'm reasonably proficient with C#, and am starting with php5. I was happy
to learn of the __get and __set methods, but am encountering a problem using
them to set an object property of type "array".
Below is a simple example of the problem I'm having with a sample object
"Article", which has an array property "authors". As you can see, I can't
even use standard php array syntax to set a single author, even though the
same syntax outside of the object works perfectly.
Am I doing something wrong here, or is this a php5 bug?
TIA,
JON
---------------------------------------
//test with normal array
$array = array();
$array[] = "Mr Jones";
print $array[0] . "<br>";
// expected result: "Mr Jones"
// actual result: "Mr Jones"
//test with array property
$article = new Article();
$article->title = "my title";
$article->authors[] = "Mr Smith";
print $article->authors[0] . "<br>";
// expected result: "Mr Smith"
// actual result: "Notice: Undefined offset: 0"
//diagnosis: authors array is *not* being filled.
// var_dump($article->authors);
// gives
// result: array(0) { }
class Article
{
protected $properties = array(
'title' => "",
'authors' => array()
);
public function __construct()
{
}
public function __get($property)
{
if( array_key_exists($property, $this->properties) )
{
return $this->properties[$property];
}
else
{
throw new Exception();
}
}
public function __set($property, $value)
{
if( array_key_exists($property, $this->properties) )
{
$this->properties[$property] = $value;
}
else
{
throw new Exception();
}
}
}
Navigation:
[Reply to this message]
|