在PHP中的变量中存储对类函数的引用
下面是一个假设的示例(父类在PHP中的变量中存储对类函数的引用,php,Php,下面是一个假设的示例(父类PageState,包含类FooterState的一个实例-根据条件,该实例可能无法创建。FooterState需要调用一个在PageState类中创建的公共函数): 我知道其他解决方案: 与其复制对函数的引用,不如创建对类的引用$this->page\u state=$page\u statepage\u state->getExpectedPageDimensions() 使用全局$PageStateInstance然后只需调用$PageStateInstance
PageState
,包含类FooterState
的一个实例-根据条件,该实例可能无法创建。FooterState
需要调用一个在PageState
类中创建的公共函数):
我知道其他解决方案:
- 与其复制对函数的引用,不如创建对类的引用
$this->page\u state=$page\u state然后,
中的函数可以调用FooterState
$this->page\u state->getExpectedPageDimensions()代码>
- 使用
然后只需调用全局$PageStateInstance
$PageStateInstance->getExpectedPageDimensions()代码>
$func='getExpectedPageDimensions'$func()代码>
完全可以存储对类函数的引用
我想你指的是对象而不是类,但是你可以用闭包
不过我觉得你没必要这么做<代码>$this->page\u state
似乎可以正常工作
不要使用全局变量。您可以将实例和函数作为可调用函数传递:一个包含实例和函数名的数组。有一个类似的系统用于调用静态类方法
# An example callback method
class MyClass {
function myCallbackMethod() {
echo 'Hello World!';
}
}
# create an instance
$obj = new MyClass();
# and later:
call_user_func(array($obj, 'myCallbackMethod'));
从这里的文档:
与其复制对函数的引用,不如创建对类$this->page\u state=$page\u state的引用;然后FooterState中的函数可以调用$this->page_state->getExpectedPageDimensions()
这是最好的通用解决方案
但我想知道是否有可能在变量中存储对类函数的引用
是的,但它实际上只适用于静态函数,除非您实例化该类。例如:
class A {
public static function doSomethingStatic() {
// ...
}
public function doSomethingElse() {
// ...
}
}
$somevar = 'A::doSomethingStatic';
$result = call_user_func($somevar); // calls A::doSomethingStatic();
$myA = new A();
$myref = array($myA, 'doSomethingElse');
$result = call_user_func($myref); // calls $myref->doSomethingElse();
请注意,在第二个示例中,您必须实例化该类并将数组作为第一个参数传递给call\u user\u func()
引用:全局变量是邪恶的:)我想类和对象在PHP中是可交换的$this->page\u state
是我解决这个问题的方法,因为首先访问对象然后访问函数的开销可以忽略不计。几乎不考虑“父”类的大小。
class A {
public static function doSomethingStatic() {
// ...
}
public function doSomethingElse() {
// ...
}
}
$somevar = 'A::doSomethingStatic';
$result = call_user_func($somevar); // calls A::doSomethingStatic();
$myA = new A();
$myref = array($myA, 'doSomethingElse');
$result = call_user_func($myref); // calls $myref->doSomethingElse();