PHP魔术方法之 __set() 方法详解
PHP中把以两个下划线__开头的方法称为魔术方法(Magic methods),这些方法在PHP中充当了举足轻重的作用。其中__set(),设置一个类的成员变量时调用__set() 的作用:__set( $property, $value )` 方法用来设置私有属性, 给一个未定义的属性赋值时,此方法会被触发,传递的参数是被设置的属性名和值。请看下面的演示代码:<?php
class Person
{
public $sex;
private $name;
private $age;
public function __construct($name="",$age=25, $sex='男')
{
$this->name = $name;
$this->age= $age;
$this->sex= $sex;
}
/**
* @param $content
*
* @return bool
*/
public function __isset($content) {
echo "当在类外部使用isset()函数测定私有成员{$content}时,自动调用<br>";
echoisset($this->$content);
}
}
$person = new Person("小明", 25); // 初始赋值
echo isset($person->sex),"<br>";
echo isset($person->name),"<br>";
echo isset($person->age),"<br>";
运行结果:
我叫小红,今年16岁了以上就是PHP中__set()方法详解的详细内容
页:
[1]