Quantcast
Channel: PHP getter and setter - Stack Overflow
Viewing all articles
Browse latest Browse all 3

Answer by Nic Wortel for PHP getter and setter

$
0
0

Unfortunately, PHP does not have the getter and setter syntax you are referring to. It has been proposed, but it didn't make it into PHP (yet).

First of all, __get() is only executed if you are trying to access a property that can't be accessed (because it is protected or private, or because it does not exist). If you are calling a property that is public, __get() will never be executed.

However, I would not suggest using PHP's magic getters and setters unless you really have no other choice. They are slower, tend to become a long if/elseif/else mess very quickly, and code completion (using a smart IDE) will not work. Normal methods are a lot simpler and easier to understand. You should also read this answer.

I have used the __get() and __set() methods for a while (instead of manually created getFoo() and setFoo() methods), because it seemed like a good idea, but I've changed my mind after a short time.

So, in your case, I recommend writing normal methods:

<?phpclass Test{    /**     * @var App[]     */    private $apps;    /**     * Returns an array containing all apps     *     * @return App[]     */    public function getApps()    {        return $this->apps;    }    /**     * Returns the number of apps     *     * @return integer     */    public function getAppsCount() //or call it countApps()    {        return count($this->apps);    }}

Viewing all articles
Browse latest Browse all 3

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>