You are here: Array property of object with __get and __set - is this a bug? « PHP « IT news, forums, messages
Array property of object with __get and __set - is this a bug?

Posted by Jon Maz on 10/20/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]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация