Moh*_*mad 6 php methods properties class object
是否可以在属性更改上运行php方法?如下例所示:
类:
class MyClass
{
public MyProperty;
function __onchange($this -> MyProperty)
{
echo "MyProperty changed to " . $this -> MyProperty;
}
}
Run Code Online (Sandbox Code Playgroud)
宾语:
$MyObject = new MyClass;
$MyObject -> MyProperty = 1;
Run Code Online (Sandbox Code Playgroud)
结果:
"MyProperty changed to 1"
Run Code Online (Sandbox Code Playgroud)
就像@lucas所说的那样,如果可以在类中将属性设置为私有,则可以使用__set()来检测更改。
class MyClass
{
private $MyProperty;
function __set($name, $value)
{
if(property_exists('MyClass', $name)){
echo "Property". $name . " modified";
}
}
}
$r = new MyClass;
$r->MyProperty = 1; //Property MyProperty changed.
Run Code Online (Sandbox Code Playgroud)