我还没有找到我在这里发布的问题的完全相同的副本,所以这里是:
class CBaseEntity
{
public function __construct()
{
}
public function __get($property)
{
$property = "m_".$property;
echo $property;
if(property_exists($this, $property))
{
$result = $this->$property;
return $result;
}
else
{
throw new Exception("Property not found $property");
}
}
}
class CCategoryEntity extends CBaseEntity
{
private $m_id;
private $m_name;
private $m_description;
public function __construct()
{
}
public static function CreateFromParams($id,$name, $description)
{
$instance = new CCategoryEntity();
$instance->m_id=$id;
$instance->m_name=$name;
$instance->m_description=$description;
return $instance;
}
public static function CreateFromArray(array $catData)
{
$instance = new CCategoryEntity();
$instance->m_id = $catData["id"];
$instance->m_name = $catData["name"];
$instance->m_description = $catData["description"];
return $instance;
}
}
$categoryEntity = CCategoryEntity::CreateFromParams(3, "EntityA", "Entity");
echo $categoryEntity->name;
Fatal error: Uncaught exception 'Exception' with message 'Property not found m_m_name'
Exception: Property not found m_m_name in ***\models\BaseModel.php on line 33
似乎该name
属性是通过get
魔术方法解析的,但是这个 getter 主体中的返回将再次发出对自身的调用,而不是不知何故智能地停止,因为字符串$property
与所寻找的属性的名称一致。我可以进行字符串比较并查看属性是否以 开头m_
,但我不希望在这种情况下已经发出第二个调用。
还有其他涉及类似代码的 SO 问题不会产生不必要的递归。php有什么变化还是默认行为?可以做些什么来以优雅的方式达到此设计的目标?