从实例调用静态函数 [英] Calling static function from instance
本文介绍了从实例调用静态函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从其子类的成员中调用静态魔术函数(__callStatic
).问题是,它转到非静态__call
.
I'm trying to call a static magic function (__callStatic
) from a member of its child class. Problem being, it goes to the non-static __call
instead.
<?php
ini_set("display_errors", true);
class a
{
function __call($method, $params)
{
echo "instance";
}
static function __callStatic($method, $params)
{
echo "static";
}
}
class b extends a
{
function foo()
{
echo static::bar();
// === echo self::bar();
// === echo a::bar();
// === echo b::bar();
}
}
$b = new b();
echo phpversion()."<br />";
$b->foo();
?>
输出:
5.3.6
instance
如何使其显示为静态"?
How can I make it display "static"?
推荐答案
如果删除魔术方法'__call',代码将返回'static'.
If you remove the magic method '__call', your code will return 'static'.
根据 http://php.net/manual/en/language. oop5.overloading.php 在静态上下文中调用不可访问的方法时,会触发__callStatic()".
According to http://php.net/manual/en/language.oop5.overloading.php "__callStatic() is triggered when invoking inaccessible methods in a static context".
我认为您的代码中正在发生的事情,
What I think is happening in your code is that,
- 您正在从非静态上下文中调用静态方法.
- 方法调用处于非静态上下文中,因此PHP搜索魔术方法'__call'.
- PHP会触发魔术方法'_ call'(如果存在).或者,如果不存在,它将调用" _callStatic".
- You are calling static method from a non-static context.
- The method call is in non-static context, so PHP searches for the magic method '__call'.
- PHP triggers the magic method '_call' if it's exists. Or, if it's not exists it will call '_callStatic'.
这是一个可能的解决方案:
class a
{
static function __callStatic($method, $params)
{
$methodList = array('staticMethod1', 'staticMethod2');
// check if the method name should be called statically
if (!in_array($method, $methodList)) {
return false;
}
echo "static";
return true;
}
function __call($method, $params)
{
$status = self::__callStatic($method, $params);
if ($status) {
return;
}
echo "instance";
}
}
class b extends a
{
function foo()
{
echo static::staticMethod1();
}
function foo2()
{
echo static::bar();
}
}
$b = new b();
echo phpversion()."<br />";
$b->foo();
$b->foo2();
这篇关于从实例调用静态函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文