如何判断变量的引用是在哪个类中启动(并且当前存在)?
<?php
class MyClass {
public $array = array(
"this",
"is",
"an",
"array"
);
}
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
?>
我最好的选择是某种Reflection,但我没有找到任何适合这种情况的功能。
我想要的更合适的例子如下:
<?php
class API_Module {
public $module;
public $name;
private $methods = array();
public function __construct($module, $name) {
$this->module = $module;
$this->name = $name;
$this->methods["login"] = new API_Method($this, "login", "Login");
}
public function GetMethod($method) {
return $this->methods[$method];
}
public function GetURL() {
return $this->module; //Should return "session"
}
}
class API_Method {
public $method;
public $name;
private $parentReference;
private $variables = array();
public function __construct(&$parentReference, $method, $name) {
$this->parentReference = $parentReference;
$this->method = $method;
$this->name = $name;
$this->variables["myvar"] = new API_Variable($this, "myvar");
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->method; //Should return "session/login"
}
public function GetVariable($variableName) {
return $this->variables[$variableName];
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
class API_Variable {
public $name;
private $parentReference;
public function __construct(&$parentReference, $name) {
$this->parentReference = $parentReference;
$this->name = $name;
}
public function GetURL() {
return $this->GetParentURL() . "/" . $this->name; //Should return "session/login/myvar"
}
private function GetParentURL() {
// Need to reference the class parent here
return $this->parentReference->GetURL();
}
}
$sessionModule = new API_Module("session", "Session");
var_dump($sessionModule->GetMethod("login")->GetVariable("myvar")->GetURL()); //Should return "session/login/myvar"
?>
现在,这很好用,但是我希望能够在每个单个子变量中使用$parentReference
来执行此操作。这可能是不可能的,但我很想知道它是否存在。
答案 0 :(得分:1)
对于你的例子:
$class = new MyClass();
$arrayReference = &$class->array;
GetClassForVariable($arrayReference); //Should return "MyClass"
在PHP中找不到别名$arrayReference
最初引用的变量。没有可用于解析别名的功能。
此外$class->array
只是一个变量。因此,您还需要根据值找出它所定义的类。这是不可能的,类似于PHP没有提供解决变量别名的任何东西,它也没有提供任何东西来了解变量的定义。
因此,简而言之,PHP没有ReflectionVariable
类可用;)我想知道它是否可行。
答案 1 :(得分:0)
get_class()函数应该可以工作:
http://php.net/manual/en/function.get-class.php
我同意GRoNGoR,您不需要获取实例化对象的属性的父类。您可以在访问该属性之前获取该类的名称。例如:
$class = new MyClass();
$parent_class = get_class($class); // returns "MyClass"
$arrayReference = &$class->array;
不确定为什么在拥有对象实例时需要属性的父类,并且可以从那里轻松获取父类。