Php - point for __get () and __set () magic

PHP 5 introduces the magic method __get () and __set (). In my opinion, this is a shortcut for writing each getter and setter member;

 <?php
class Person {
    private $firstname;
    private $lastname;

    function __set($var, $name) {
        $this->$var = $name;
    }

    function __get($var) {
        return $this->$var;
    }
}

$person = new Person();
$person->firstname = "Tom";
$person->lastname = "Brady";


echo $person->firstname . " " . $person->lastname;

// print: Tom Brady
?>

My question is, this is just like public member variables.

class Person {
    public $firstname;
    public $lastname;
}

Isn't that against the principles of OOP? And what's the point?

+3
source share
3 answers

In your example, this will be the same as making them public. However, your __set and __get functions should not handle all variables. (Perhaps using the switch statement to decide what you want to process.) Alternatively, you can perform parameter checking in __set or calculate the return value for __get that does not exist at all.

, $this- > var $this → $var ( , , , )

+3

- , , " " . .

, , python - . .

Smalltalk , , , . .

, php . :

  • ORMappers
  • API
  • , - .
  • .

, - `_ ' .

<?php
class Person {
    private $_firstname;
    private $_lastname;

    function __set($name, $value) {
        if (!strpos('_', $name) === 0) {
            $this->$name = $value;
        } else {
            throw new Exception ("trying to assign a private variable");
        }
    }

    function __get($name) {
        if (!strpos('_', $name) === 0) {
            retrun $this->$name;
        } else {
            throw new Exception ("trying to read a private variable");
        }
    }
}

?>
+2

First of all, your example should not work because you are accessing $this->var.

Second: Yes, adding wizards and getters is like adding setters and getters. Just magic.

Used for __set and __get: if you built a library like ORM, it might come in handy. In addition, it can be used as properties of the poor: if you first published the field, now you can add behavior to __set and __get, as if it always had (for example, validation).

0
source

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


All Articles