0

This is the accessor function:

<?php
    class classname
    {
        public $attribute;
        function __get($name)
        {
            return $this->$name;
        }
    }

    $a = new classname;
    $a->attribute = "Anna";
    $name = $a->attribute;

echo $name;

?>

And this is just a regular class without accessor functions:

<?php
    class classname
    {
        public $attribute;
    }

    $a = new classname;
    $a->attribute = "Anna";
    $name = $a->attribute;

    echo $name;
?>

Both of them provide the same result. I don't get it, in what case should I use accessor functions?

Josh Mayer
  • 81
  • 4
  • 1
    you would only require accessors for non public properties. now some would argue that all properties of an object should be private/protected. the magic getter function is called when a property that is not accessible is requested. – Ian Wood Jul 27 '14 at 10:11
  • 1
    From [the manual](http://php.net/manual/en/language.oop5.overloading.php#object.get): __get() is utilized for reading data from **inaccessible** properties. – Álvaro González Jul 27 '14 at 10:14
  • 1
    In your example you are **not** using the __get function! If there is a public member variable that takes precedence. __get runs when there is not matching accessible property. – Adam Jul 27 '14 at 10:18
  • 1
    There is another question http://stackoverflow.com/questions/6741595/php-get-set-methods which is a better match as a duplicate IMO. The question linked as duplicate is about getters/setters in general. The use of __get()/__set() in php is a slightly different question (I use gettters and setters and try and avoid __get unless I really need it) – Adam Jul 27 '14 at 10:24

1 Answers1

1

1) It simply lets you control how and who can have access to the property. ( The property should be private when using accessors. )

2) you may alter the value depending on who and how it is accessed

3) You can notify someone when a property is accessed

Any many more ...

minychillo
  • 395
  • 4
  • 17