Home > Backend Development > PHP Tutorial > PHP magic method function and usage example analysis

PHP magic method function and usage example analysis

黄舟
Release: 2023-03-06 07:50:01
Original
847 people have browsed it

The examples in this article describe the functions and usage of php magic methods. Share it with everyone for your reference, the details are as follows:

<?php
//php中的魔术方法
header(&#39;content-type:text/html;charset=utf-8&#39;);
class Person{
 public $name;
 protected $sex;
 private $salary;
 //构造方法,实例化对象是自动触发的方法
 public function __construct($name,$sex,$salary){
  $this->name=$name;
  $this->sex=$sex;
  $this->salary=$salary;
 }
 //魔术常量__CLASS__
 public function getClassName(){
  echo __CLASS__;
 }
 // __FUNCTION__
 public function getMethod(){
  echo __FUNCTION__;
 }
 //__tostring()
  public function __tostring(){
   return &#39;对象必须用var_dump()&#39;.&#39;姓名是&#39;.$this->name;
  }
 //__clone() 在使用clone方法的时候会自动调用
  public function __clone(){
   echo &#39;这个对象是被克隆出来的&#39;;
   $this->name=&#39;李四&#39;;
  }
  //__get() 当调用一个不存在或权限不够的属性自动触发的方法
  public function __get($a){
   echo $a.&#39;属性不存在或权限不够&#39;;
  }
  //__set() 当设置一个不存在或权限不够的属性时自动触发的方法
  public function __set($name,$value){
   echo $name.&#39;为&#39;.$value;
  }
  //__isset() 当在类外判断一个不存在或权限不够的属性时自动触发的方法
  public function __isset($name){
   echo $name.&#39;不能为空&#39;;
  }
  //__call() 当去访问一个权限不够或者不存在的方法的时候,会自动触发的魔术方法
  public function __call($method,$a){
   echo &#39;您请求的方法&#39;.$method.&#39;不存在&#39;;
   $this->getname();
  }
  public function getname(){
  echo $this->name;
  }
}
//实例化对象
$person=new Person(&#39;张三&#39;,&#39;男&#39;,12223);
$person1=new Person(&#39;张三&#39;,&#39;男&#39;,12223);
//$person2=new Person(&#39;李四&#39;,&#39;女&#39;,11111);
var_dump($person);
var_dump($person1);
exit;
$person->getClassName();
$person->getMethod();
//echo $person->name;
//echo $person;
$person1=$person; //同一个对象
//var_dump($person);
//var_dump($person1);
$person2=clone $person; //克隆会产生不一样的对象
//var_dump($person);
//var_dump($person2);
//echo $person2->name;
//$person->salary=10000;
//var_dump(isset($person->salary));
//$person->getName();
Copy after login

The above is the analysis of the functions and usage examples of PHP magic methods. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template