PHP magic method

Keywords: Programming PHP Redis

Constructors and Destructors

__construct constructor

Class calls this method every time a new object is created, so it's a good place to do some initialization before using the object.

__deconstruct

Destructors execute when all references to an object are deleted or when the object is explicitly destroyed.

<?php
class MyDestructableClass {
    public $name;
   function __construct() {
       print "In constructor\n";
       $this->name = "MyDestructableClass";
   }

   function __destruct() {
       print "Destroying " . $this->name . "\n";
   }
}

$obj = new MyDestructableClass();
?>

Method overloading

public __call ( string $name , array $arguments ) : mixed
public static __callStatic ( string $name , array $arguments ) : mixed

When an invocation method is invoked in an object, __call() is called.

When an invocation method is invoked in a static context, __callStatic() is called.

When the method does not exist, it will also go through this function and can do special processing. For example, to implement a redis operation class, most of the operation methods can be directly from predis itself. At this time, it is easy to implement this function with the help of "call"

Property Override

public __set ( string $name , mixed $value ) : void
public __get ( string $name ) : mixed
public __isset ( string $name ) : bool
public __unset ( string $name ) : void
  • When assigning a value to an inaccessible property, \.
  • When reading the value of an inaccessible property, \.
  • When isset() or empty() is called on an inaccessible property, u isset() is called.
  • When unset() is called on an inaccessible property, \.

Parameter name is the name of the variable to operate on.

  • __The name of the set() method is the name of the variable to operate on.
  • __The value parameter of the set() method specifies the value of the $name variable.

Property overloading can only occur in objects. In static methods, these magic methods will not be called. So none of these methods can be declared static.

Property overloading will also enter magic methods when the property does not exist. It can be processed in methods, such as the setter using dependency injection
<?php
class PropertyTest {
     /**  The overloaded data is saved here  */
    private $data = array();

 
     /**  Overloads cannot be used on defined properties  */
    public $declared = 1;

     /**  Overload occurs only when this property is accessed from outside the class */
    private $hidden = 2;

    public function __set($name, $value) 
    {
        echo "Setting '$name' to '$value'\n";
        $this->data[$name] = $value;
    }

    public function __get($name) 
    {
        echo "Getting '$name'\n";
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }

        $trace = debug_backtrace();
        trigger_error(
            'Undefined property via __get(): ' . $name .
            ' in ' . $trace[0]['file'] .
            ' on line ' . $trace[0]['line'],
            E_USER_NOTICE);
        return null;
    }

    /**  PHP 5.1.0 Later version */
    public function __isset($name) 
    {
        echo "Is '$name' set?\n";
        return isset($this->data[$name]);
    }

    /**  PHP 5.1.0 Later version */
    public function __unset($name) 
    {
        echo "Unsetting '$name'\n";
        unset($this->data[$name]);
    }

    /**  Non magic method  */
    public function getHidden() 
    {
        return $this->hidden;
    }
}


echo "<pre>\n";

$obj = new PropertyTest;

$obj->a = 1;
echo $obj->a . "\n\n";

var_dump(isset($obj->a));
unset($obj->a);
var_dump(isset($obj->a));
echo "\n";

echo $obj->declared . "\n\n";

echo "Let's experiment with the private property named 'hidden':\n";
echo "Privates are visible inside the class, so __get() not used...\n";
echo $obj->getHidden() . "\n";
echo "Privates not visible outside of class, so __get() is used...\n";
echo $obj->hidden . "\n";
?>

__toString()public
__toString ( void ) : string
__The toString() method is used for how a class should respond when it is treated as a string.

For example, echo $obj; what should be displayed.
This method must return a string, otherwise it will issue a fatal error with the level of "e" recoverable "error.

<?php
// Declare a simple class
class TestClass
{
    public $foo;

    public function __construct($foo) 
    {
        $this->foo = $foo;
    }

    public function __toString() {
        return $this->foo;
    }
}

$class = new TestClass('Hello');
echo $class;
?>

__invoke()
__invoke ([ $... ] ) : mixed

When you try to call an object as a function, the \.

<?php
  class CallableClass 
  {
      function __invoke($x) {
          var_dump($x);
      }
  }
  $obj = new CallableClass;
  $obj(5);
  var_dump(is_callable($obj));
  ?>

 

Posted by Caesar on Mon, 06 Apr 2020 01:57:18 -0700