Recommendations for __get () and __set ()

Based on this question, when using __get()and __set()for accessing private variables, I would like to receive information on how they are used in general. I am wondering when or where there will be a better time to use the overload function and where you used it (if any).

To be clear, we are talking about these functions: http://us2.php.net/manual/en/language.oop5.magic.php

+3
source share
4 answers

Lazy Models Getters (using __get ())

, PHP- , , __get() .

, CakePHP, , , , , (, ). ( , ).

, , __get(), . 3-4 . , AppController ( CakePHP ), .

, .

( __call())

, CakePHP, , Cake . : find() findAll() , findBy<FieldName>() findAllBy<FieldName>().

, db

notes(id, date, title, body)

Cake. , findById(), findByTitle() .. db CamelCase, .

__call(). , , , find() findAll() , . .

+3

__get() __set() , :

class Something {
    private $data;

    public function __set($key, $value) {
        //put validation here
        $this->data[$key] = $value;
    }

    public function __get($key) {
        if (!array_key_exists($this->data, $key)) {
             throw new Exception("Invalid member $key.");
        } else {
             return $this->data[$key];
        }
    }
}

, , - $person- > age = "asdf" ( , .)

__set() , , , "".

+2

:

class formatedContainer {
    private $holder;
    protected $mode = "formated";

    public function __set($var, $value) {
        $formated = chunk_split($value, 4, "-");
        if(substr($formated, -1) == "-") 
            $formated = substr($formated, 0, strlen($formated) - 1);
        $this->holder[$var] = array('formated' => $formated, 'plain' => $value);
    }

    public function __get($var) {
        return $this->holder[$var][$this->mode];
    }

    public function getPlain() {
        $this->mode = "plain";
    }

    public function getFormated() {
        $this->mode = "formated";
    }
}

$texts = new formatedContainer();
$texts->myText = md5(uniqid());
$texts->anotherText = md5("I don't change!");

//Prints something like: 440e-6816-b2f5-7aa5-9627-9cc8-26ef-ef3b
echo $texts->myText;

$texts->getPlain();

//Prints something like: 8559d37c5a02714dca8bd1ec50a4603a
echo "<br/>" . $texts->anotherText;

, , .:}

0

, __get() __set() " ". , , , - IDE .. , , __get() __set() . , unset() , .

0

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


All Articles