在5.3之前伪造后期静态绑定 [英] Faking Late Static Binding before php 5.3

查看:48
本文介绍了在5.3之前伪造后期静态绑定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个继承的静态函数"call"来调用另一个已被覆盖的静态函数"inner".我可以使用后期静态绑定来完成此操作,但是我的主机还没有php5.3,因此我需要解决它.

I need an inherited static function "call" to call another static function "inner" that has been overridden. I could do this with late static binding, but my host does not have php5.3 yet and so I need to work around it.

class ClassA{
    static function call()
    {
        return self::inner();
    }

    static function inner(){
        return "Class A";
    }   
}

class ClassB extends ClassA{
    static function inner(){
        return "Class B";
    }
}

echo "<p>Class A = " . ClassA::call();
echo "<p>Class B = " . ClassB::call();

我希望输出为:
A级= A级
B级= B级

I would like the output to be:
Class A = Class A
Class B = Class B

但它是什么:
A级= A级
B级= A级

But what it is:
Class A = Class A
Class B = Class A

我的直觉告诉我,当"call()"被调用时,我应该能够在call()中写一些东西来检测所引用的对象.因此,与其说是self :: inner(),不如说它是类似于class :: inner()的东西.从原始方法调用中检测要调用的inner()的正确版本.

My gut tells me that I should be able to write something in call() to detect what object was referenced when "call()" was, well, called. So instead of self::inner() it would so something along the lines of calledclass::inner(). Detecting the proper version of inner() to call from the original method call.

推荐答案

您可以使用对象实例而不是类.如果要使用全局符号,则可以使用全局变量.由于它们在PHP中相当笨拙,因此一个诀窍是将其包装在函数中.例如:

You can use object instances rather than classes. If you want a global symbol, you can use a global variable. Since they are rather unwieldy in PHP, one trick is to wrap it in a function. Eg.:

class ClassA {
  function call() {
    return $this->inner();
  }
  function inner() {
    return "Class A";
  }   
}
function ClassA() {
  static $instance;
  return $instance ? $instance : new ClassA();
}

class ClassB extends ClassA {
  function inner() {
    return "Class B";
  }
}
function ClassB() {
  static $instance;
  return $instance ? $instance : new ClassB();
}

echo "<p>Class A = " . ClassA()->call();
echo "<p>Class B = " . ClassB()->call();

但是更好的主意可能是完全避免使用全局符号.它在Ruby/Rails中运行良好的原因是,Ruby确实不具有与PHP相同的静态状态.可以在运行时将类重新绑定并添加到类中,从而可以轻松扩展框架.在PHP中,类始终是最终的,因此在应用程序代码中引用它们的程度非常强.

But a better idea might be to avoid global symbols altogether; The reason why it works well in Ruby/Rails, is that Ruby doesn't really have static state in the same way that PHP has. A class can be rebound and added to at runtime, which allows for easy extension of the framework. In PHP, classes are always final, so referring to them in application code, is a very strong degree of coupling.

这篇关于在5.3之前伪造后期静态绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆