我有一个定制的MVC PHP框架,我正在重写,并对性能和魔术方法有疑问.使用框架的模型部分,我在想是否__get
/ __set
magic方法会导致太多的性能损失值得使用.我的意思是访问(读取和写入)模型数据将是最常见的事情之一.对于像MVC框架的模型部分这样的大量使用功能,__get
/ __set
magic方法的使用是否太大了?
<?php
abstract class AbstractClass
{
public function __get($theName)
{
return (isset($this->$theName)) ? $this->$theName : NULL;
}
public function __set($theName, $theValue)
{
if (false === property_exists(get_class(), $theName)) {
throw new Exception(get_class()." does not have '".$theName."' property.");
} else {
$this->$theName = $theValue;
}
}
}
class ConcreteClass extends AbstractClass
{
private $x;
private $y;
public function __construct($theX, $theY)
{
$this->x = $theX;
$this->y = $theY;
}
}
$concreteClass = new ConcreteClass(10, 20);
var_dump( $concreteClass->x );
Run Code Online (Sandbox Code Playgroud)
有没有办法让这项工作或我必须将这些魔术方法添加到扩展类?
我不知道我在哪里做错了.有人能告诉我吗?
<?php
class something
{
public $attr1;
private $attr2;
public function __get($name)
{
return $this->$name;
}
public function __set($name,$value)
{
$this->$name = $value." added something more";
}
}
$a = new something();
$a->$attr1 = "attr1";
$a->$attr2 = "attr2";
echo $a->$attr1; //what I would expect is attr1 as output
echo $a->$attr2; //what I would expect is attr2 added something more as output
?>
Run Code Online (Sandbox Code Playgroud)