在抽象类中声明的方法中从子级获取常量覆盖
我有这个(缩短):
abstract class MyModel
{
const DBID = "";
const TOKEN = "";
public function getDB()
{
if(!$this->_DB)
{
$c = get_called_class(); // doesn't work pre php 5.3
echo $c::DBID; // doesn't work pre php 5.3
echo $c::TOKEN // doesn't work pre php 5.3
}
return $this->_qb;
}
问题是 get_ Called_class() 并且 $c::DBID/TOKEN 在 php 中不起作用 < 5.3
有没有一种方法可以在与 5.2.9 兼容的抽象类中完成相同的任务?
I have this (shortened):
abstract class MyModel
{
const DBID = "";
const TOKEN = "";
public function getDB()
{
if(!$this->_DB)
{
$c = get_called_class(); // doesn't work pre php 5.3
echo $c::DBID; // doesn't work pre php 5.3
echo $c::TOKEN // doesn't work pre php 5.3
}
return $this->_qb;
}
The problem is that get_called_class() and the $c::DBID/TOKEN doesn't work in php < 5.3
Is there a way I can accomplish the same task from within the abstract class that is compatible with 5.2.9?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
编辑:
常量实际上并不意味着在对象实例化过程中进行更改,您可能需要考虑成员变量。
抽象类不能直接实例化。您可以创建一个子类来扩展您的抽象类,然后调用 getDb()。
EDIT:
Constants aren't really meant to be changed throughout object instantiations, you may want to consider member variables instead.
Abstract classes cannot be instantiated directly. You could create a child class to extend your abstract class, then make the call to getDb().
我在 PHP 5.2 代码库中有一个解决方案,它使用反射从超类获取子类的常量,但我建议不要这样做,除非绝对必要,因为就性能而言,反射是 PHP 中相对昂贵的工具。
PHP 5.3 引入了 static 关键字,如 static::CONST 而不是 self::CONST 来访问类的静态成员。我从未真正尝试过,但我相信它应该能够满足您的需求。在 PHP 手册中查找最新的静态绑定。
作为记录,下面是使用反射获取子类常量的方法的代码。
I had a solution in a PHP 5.2 codebase that used reflection to get at the constants of a subclass from a superclass, but I'd advise against doing that unless it's absolutely necessary because reflection is q relatively expensive tool in PHP in terms of performance.
PHP 5.3 introduced the static keyword as in static::CONST instead of self::CONST to access static members of a class. I've never actually tried it but I believe it should be able to do what you need. Look up late static binding in the PHP manual.
For the record, here's the code for a method that used reflection to get a subclass constant.