Andrew
Andrew

Reputation: 238667

PHP, Zend Framework quickstart tutorial: How does this work?

Here is a link to the tutorial that I am referring to.

This seems strange to me...in the view script we have this code:

<?php echo $this->escape($entry->email) ?>

This displays the email address that has been set in the Guestbook model. But the property on the model is $_email and it is protected. We're not calling $entry->getEmail(); so I don't understand how this is working or where it is pulling this information. I know that it works, but I just don't understand how.

Upvotes: 0

Views: 579

Answers (3)

smack0007
smack0007

Reputation: 11366

The method gets called when an undefined attribute is accessed on a class.

public function __get($name)
{
    $method = 'get' . $name;
    if (('mapper' == $name) || !method_exists($this, $method)) {
        throw new Exception('Invalid guestbook property');
    }
    return $this->$method();
}

The method in turn redirects to another method. In this case getEmail().

Upvotes: 1

Pascal MARTIN
Pascal MARTIN

Reputation: 400952

If there is no property called $email, and there is a __get magic-method in the class, you are going through that one.

Indeed, quoting the page you linked to :

__get() and __set() will provide a convenience mechanism for us to access the individual entry properties, and proxy to the other getters and setters. They also will help ensure that only properties we whitelist will be available in the object.

To learn more about magic methods in PHP 5, you can read this page of the manual -- magic methods are used quite a lot in Zend Framework ; and in other modern Frameworks too, should I add.

Upvotes: 2

Mike B
Mike B

Reputation: 32145

There is probably a __get() method within the $entry object which allows normally inaccessible properties to be accessed.

Upvotes: 0

Related Questions