0

I'm reading this ebook, Beginning PHP5 and Mysql: From Novice to Professional, and in the OOP section, I'm trying out this sample code to reproduce the same results on my computer vs the book.

class Staff
{
var $name;
var $city;
protected $wage;
    function __get($propName)
    {
        echo "__get called!<br />";
        $vars = array("name","city");
        if (in_array($propName, $vars))
        {
        return $this->$propName;
        } else {
        return "No such variable!";
        }
    }
}
$employee = new Staff();
$employee->name = "Mario";
echo $employee->name."<br />";
echo $employee->age;

In the book - the results are shown as:

Mario
__get called!
No such variable!

But on my computer:

Mario

Only the first line. The other two lines were "ignored". Why is that?!?!

Is there some configuration setting on my php.ini that I need to modify to get this working? Can someone please help to explain?

deceze
  • 510,633
  • 85
  • 743
  • 889
awongCM
  • 917
  • 5
  • 22
  • 46
  • Is the last line supposed to be `echo $employee->wage;`? – bjudson Apr 13 '12 at 03:38
  • 1
    Is this your book? http://www.amazon.com/Beginning-PHP-MySQL-Novice-Professional/dp/1893115518 It is 8 years old and apparently uses PHP4. – 000 Apr 13 '12 at 03:40
  • @joeframbach: My book and this amazon link has the same title concidentally. My book's 2006 edition. It's 6 years old. – awongCM Apr 13 '12 at 03:56
  • @handsofaten: No. I copied the code straight off from the book, just to test the true 'Object-Oriented'ness behind it. So no typo there. – awongCM Apr 13 '12 at 03:56
  • Try adding this at the beginning of the script: error_reporting(E_ALL); – MikeSW Apr 13 '12 at 14:55

2 Answers2

1

__get() will only get called for non-public or non-existant properties. Now, there is a property called name, so your magic method won't get called. Change var $name into private $name and it will work.

Berry Langerak
  • 18,561
  • 4
  • 45
  • 58
0

OK I think I found the answer. According to php docs

All overloading methods must be defined as public.

so make the magic method public

public function __get() {}
MikeSW
  • 16,140
  • 3
  • 39
  • 53