How to use PHP __get () and __set () for specific fields in my class?

I read the PHP specifications well at overload , and most of the examples seem to be designed to simply define custom fields (similar to stdClass).

But what about the private fields defined in my class? How to receive or appoint them? I could switch the possible values ​​and act on certain values:

class A
{
    private $name;
    private $age;

    public function __get( $var )
    {
        switch ( $var )
        {
            case 'name':
                return $this->name;
                break;
            case 'age':
                return $this->age+10; // just to do something different ;)
                break;
            default:
                break;
        }
    }
}

Is this the best method or is there another generally accepted best practice? (I don’t know if it is possible to loop the class variables inside the class, but no matter what is not suitable in most situations, since you do not want to return everything.)

+3
3

, - , ( , ).

, , , getter/setter (, age).

, / (, ), / (getAge()/setAge()).

+2

__get() __set() public. , IDE , . PHP, ?

unset() __get() __set() __construct().

, : -)

+9

, , .

, , , . , . , /. , , null.

Honestly, the implementation for this is valid in each case. If you had a custom class that you saved all the information in a single array, you could output $ user-> name from $ user-> account ['name'] or something like that.

In addition, in each case, you can make some changes before giving them values, for example, password hashing.

+1
source

Source: https://habr.com/ru/post/1713516/


All Articles