Digital Ninja
Digital Ninja

Reputation: 3731

Why doesn't my getter work?

<?php 

error_reporting(E_ALL);
ini_set('display_errors', true);

class Person {

   private $data;

   public function __construct($data) {
      $this->data = $data;
   }

   public function __get($prop) {
      return $this->data[$prop];
   }
}

$data = array('name' => 'Mark');
$person = new Person($data);
echo $person->get('name');

?>

Shouldn't this work?

I get Fatal error: Call to undefined method Person::get(), but I don't know why. As per the documentation for the magic methods, this code should work fine.

http://php.net/manual/en/language.oop5.overloading.php#object.get

Upvotes: 0

Views: 252

Answers (1)

Valentin Rodygin
Valentin Rodygin

Reputation: 864

Try

echo $person->name;

instead.

That's the magic of the __get magic method :-)

Just in case, you can define

public function __call( $name, $arguments ) {
    echo $name;
    // do something useful
}

and then make magic calls like that:

$person->someMethod(); // echoes "someMethod"

Upvotes: 4

Related Questions