Magic Method in PHP

Source: Internet
Author: User

Magic Method in PHP

1. _ construct () and _ destruct ()

If an instance is called when it is created or destroyed, zero or multiple parameters can be passed.

class A {  function A()  {   echo "build A";  }  function __destruct()  {   echo "destroy A";  } } $obj = new A(); //unset($obj);

Note: The destructor method will be called as soon as there are no other references to a participant object, or in any order during the shutdown sequence.

With regards to constructor, a class defined in a particular namespace named after the class name will no longer be considered as a constructor at the beginning of PHP5.3.3. In a namespace-free class, it is still a constructor. For example:

namespace Foo;class Bar {  public function Bar() {    // treated as constructor in PHP 5.3.0-5.3.2    // treated as regular method as of PHP 5.3.3  }}

If namespace Foo; is not available, Bar () is also treated as a constructor. In addition, if the following conditions exist:

function __construct()  {   echo "construct A";  }  function A()  {   echo "build A";  }  function __destruct()  {   echo "destroy A";  } }

That is, if _ construct () and a function with the same name as the class name are included, only _ construct () is called ().

2. _ call () and _ callStatic ()

This method is called when you try to call a method that does not exist. Two parameters: one is the method name and the other is the parameter array of the called method.

class MethodTest{  public function __call($name, $arguments)  {    // Note: value of $name is case sensitive.    echo "Calling object method '$name' "       . implode(' ', $arguments). "<br>";  }  public static function __callStatic($name, $arguments)  {    // Note: value of $name is case sensitive.    echo "Calling static method '$name' "       . implode(' ', $arguments). "<br>";  }}$obj = new MethodTest;$obj->runTest('in','object','context');MethodTest::runTest('in','static','context');

$ Arguments is passed as an array. Running result:

Calling object method 'runtest' in object context
Calling static method 'runtest' in static context

Also note the function scopes protected and private:

class TestMagicCallMethod {  public function foo()  {    echo __METHOD__.PHP_EOL."<br>";  }  public function __call($method, $args)  {    echo __METHOD__.PHP_EOL."<br>";    if(method_exists($this, $method))    {      $this->$method();    }  }    protected function bar()  {    echo __METHOD__.PHP_EOL."<br>";  }  private function baz()  {    echo __METHOD__.PHP_EOL."<br>";  }}$test  =  new TestMagicCallMethod();$test->foo();/** * Outputs: * TestMagicCallMethod::foo */$test->bar();/** * Outputs: * TestMagicCallMethod::__call * TestMagicCallMethod::bar */$test->baz();/** * Outputs: * TestMagicCallMethod::__call * TestMagicCallMethod::baz */

3. _ get () and _ set ()

It is called when you try to read an attribute that does not exist in an object.

Note: We can use this function to perform operations similar to reflection in java.

class Test{  public function __get($key)  {   echo $key . " not exists";  }  public function __set($key,$value)  {   echo $key . " = ".$value;  }}$t = new Test();echo $t->name."<br>";$t->name = "abc";

Output:
Name not exists
Name = abc

4. _ toString ()

This method is similar to the toString () method of java. When we print the object directly, we call this function back. The function must return a string.

class Test{  private $name = "abc";  private $age = 12;  public function __toString()  {    return "name : $this->name, age : $this->age";  }}$t = new Test();echo $t;

Output:

Name: abc, age: 12


Explain in detail the magic methods in php5

PHP has completely re-developed the kernel for processing objects, providing more functions while improving performance. In earlier versions of php, the methods for processing objects and basic types (numbers, strings) are the same. This method has the following drawbacks: when an object is assigned to a variable or an object is passed through a parameter, the object will be completely copied. In the new version, the above operations will pass references (which can be understood as object identifiers), rather than values.
Many PHP programmers may not even notice the old object processing method. In fact, most php applications can run well. Or few changes are required.
Private and protected members
PHP5 introduces the concept of private and protected member variables. We can use it to define the visibility of class members.
Example
Protected members can be accessed by the quilt class, while private members can only be accessed by the class itself.

Code :--------------------------------------------------------------------------------

<? Php
Class MyClass {
Private $ Hello = "Hello, World! \ N ";
Protected $ Bar = "Hello, Foo! \ N ";
Protected $ Foo = "Hello, Bar! \ N ";

Function printHello (){
Print "MyClass: printHello ()". $ this-> Hello;
Print "MyClass: printHello ()". $ this-> Bar;
Print "MyClass: printHello ()". $ this-> Foo;
}
}

Class MyClass2 extends MyClass {
Protected $ Foo;

Function printHello (){
MyClass: printHello ();/* shocould print */
Print "MyClass2: printHello ()". $ this-> Hello;/* Shouldn't print out anything */
Print "MyClass2: printHello ()". $ this-> Bar;/* Shouldn't print (not declared )*/
Print "MyClass2: printHello ()". $ this-> Foo;/* shocould print */
}
}

$ Obj = new MyClass ();
Print $ obj-> Hello;/* Shouldn't print out anything */
Print $ obj-> Bar;/* Shouldn't print out anything */
Print $ obj-> Foo;/* shoshould ...... the remaining full text>

Php magic Method

In this way, it is for security, that is, the concept of object-oriented encapsulation. If Public is set directly, no object can set the value of this attribute freely, it does not pass the logic judgment of the task. In this way, it can increase security.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.