php里面的魔术方法__魔术方法名__():__set __get __call

2022-03-25 20:31:11 浏览数 (1)

代码语言:javascript复制
<?php
header('Content-Type:text/html;charset=utf-8');
//抽象类
abstract class Humanity {
	
	public $name;
	public $sex;
	public $iq=10;
	protected $money;
	protected $dna;
	const BIRTHPLACE='地球';
	static public $counter=0;//静态属性,它是公共的资源和具体的实例没有关系
	//构造函数
	public function __construct($name,$sex){
		self::$counter  ;
		$this->name=$name;
		$this->sex=$sex;
	}
	protected function chew($food){
		echo "<p>{$food}已经被咀嚼完成!</p>";
	}
	//抽象方法
	abstract public function eat($food);
	static public function hello(){
		echo '<p>您好!我是来自'.self::BIRTHPLACE.'的人类</p>';
	}
}
class Student extends Humanity {
	const BIRTHPLACE='火星';
	private  $hh=666;
	public $studentId;
	public function __set($name,$value){
		
		 $this->$name=$value;
	}
	public function __get($name){
		
		
			return ($this->$name)*666;
		
	}
	
	public function test($subject){
		echo "<p>{$this->name}正在考{$subject}!</p>";
	}
	public function eat($food){
		$this->chew($food);
		echo "<p>{$this->name}正在快速的吃{$food}!</p>";
	}
}
$hanMM=new Student('韩梅梅','女');
echo $hanMM->hh;

解析:

核心在于,私有性的《《《属性》》》调用时才能执行__set__get方法。 怎么执行呢? 调用私有性的属性即可,但是切记调用时不能赋值哦

代码语言:javascript复制
<?php
header('Content-Type:text/html;charset=utf-8');
//抽象类
abstract class Humanity {
	
	public $name;
	public $sex;
	public $iq=10;
	protected $money;
	protected $dna;
	const BIRTHPLACE='地球';
	static public $counter=0;//静态属性,它是公共的资源和具体的实例没有关系
	//构造函数
	public function __construct($name,$sex){
		self::$counter  ;
		$this->name=$name;
		$this->sex=$sex;
	}
	protected function chew($food){
		echo "<p>{$food}已经被咀嚼完成!</p>";
	}
	//抽象方法
	abstract public function eat($food);
	static public function hello(){
		echo '<p>您好!我是来自'.self::BIRTHPLACE.'的人类</p>';
	}
}
class Student extends Humanity {
	const BIRTHPLACE='火星';
	private  $hh=666;
	public $studentId;
	public function __call($funcName,$agrs){
		echo "__call方法";
	}
	
	private function test($subject){
		echo "<p>{$this->name}正在考{$subject}!</p>";
	}
	public function eat($food){
		$this->chew($food);
		echo "<p>{$this->name}正在快速的吃{$food}!</p>";
	}
}
$hanMM=new Student('韩梅梅','女');
echo $hanMM->test();

解析: 调用私有性的方法时才自动执行的哦

set

0 人点赞