PHP: Share 5 recently used magic methods 1. _ contruct ()
Constructor. The difference between this and a common constructor is that you do not need to define a function with the same name as the class name every time as a constructor.
2. _ call ($ funcName, $ params)
Is a function that is triggered when a function is not defined in the instance call class.
Class Model {// $ funcName: undefined function name // $ params (array): undefined function parameter _ call ($ funcName, $ params) {// I have not used $ params return "the function: $ funcName is not exist! "}}$ Model = new Model (); $ model-> func (); // if the function func does not exist, _ call is triggered.
3. _ get ($ name)
Used to call non-public attributes in a class:
class Model{ private host ="http://localhost"; public function __get($name){ return $this->$name; }}$model =new Model();$model->host;
4. _ set ($ name, $ value)
Corresponds to the _ get method and is used to assign values to non-public attributes.
class Model{ private host =null; public function __set($name, $value){ $this->$name =$value; }}$model =new Model();$model->host ="http://localhost";
5. _ autoload ()
This is used to introduce class files. generally, we use include, include_once, require, and require_once to import files.
However, if we want to introduce multiple files, we need to write the appropriate import statement, which is inconvenient and not beautiful, __autoload can solve this problem.
The biggest benefit of the class object is its laziness attribute, which is introduced only when the object is instantiated.
// For example, my Model file Model. class. php models/models under the previous Directory of the current directory. class. php (actually the path to the introduced class file) function _ autoload ($ className) {// $ className is the class name $ filename = ".. /Model /". $ className. ". class. php "; // combined path require_once" $ filename "; // introduce class file} // This function is triggered when an object is instantiated.