PHP magic methods __set and __get

Will it reckon with good practice ...

I have class A with the following definitions:

 class A{
      private $_varOne;
      private $_varTwo;
      private $_varThree;
      public $varOne;


      public function __get($name){

   $fn_name = 'get' . $name;

         if (method_exists($this, $fn_name)){
             return $this->$fn_name();
   }else if(property_exists('DB', $name)){
             return $this->$name;
   }else{
    return null;
   }
      }

  public function __set($name, $value){

   $fn_name = 'set' . $name;

   if(method_exists($this, $fn_name)){
    $this->$fn_name($value);
   }else if(property_exists($this->__get("Classname"), $name)){
    $this->$name = $value;
   }else{
    return null;
   }

  }

      public function get_varOne(){
           return $this->_varOne . "+";
      }


 }

 $A = new A();
 $A->_varOne;     //For some reason I need _varOne to be returned appended with a +

 $A->_varTwo;     //I just need the value of _varTwo

In order not to create 4 set and 4 get methods, I used magic methods to either call the respected getter for the property I need, or simply return the value of the property without any changes. Could this be considered good practice

+3
source share
4 answers

, __get , , , , db. , php , getter.

class LazyLoader
{
    public $pub = 123;

    function __get($p) {
        $fn = "get_$p";
        return method_exists($this, $fn) ? 
            $this->$fn() : 
            $this->$p; // simulate an error
    }

    // this will be called every time  
    function get_rand() {
        return rand();
    }

    // this will be called once
    function get_cached() {
        return $this->cached = rand();
    }
}

$a = new LazyLoader;
var_dump($a->pub);       // getter not called
var_dump($a->rand);      // getter called 
var_dump($a->rand);      // once again 
var_dump($a->cached);    // getter called 
var_dump($a->cached);    // getter NOT called, response cached
var_dump($a->notreally); // error!
+7

?

, , , , . , , - , .

, , , getters/seters. PHP , .

+3

Java, ?

, , . __get, __set , - , .

, , , , , .., - -, /

+2

, , , , PHP . .

, :

__set() - , PHP . , __get() :      $ a = $obj- > b = 8;

. API , , -, .

+1

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


All Articles