在 PHP 中超类的静态方法中访问子类的静态属性的正确方法是什么?
假设我有以下内容:
<?php
abstract class MyParent
{
public static $table_name;
public static get_all(){
return query("SELECT * FROM {$this->table_name}");
}
public static get_all2(){
return query("SELECT * FROM ".self::table_name);
}
}
class Child extends MyParent
{ public static $table_name = 'child'; }
?>
假设 query
已正确定义,这些方法都不会执行我想要的操作: get_all() 抛出 致命错误:在不在对象上下文中时使用 $this /path/to/foo.php 在第 xx 行
上,因为 $this
是一个实例变量。
并且 get_all2() 抛出 致命错误:未定义的类常量 'table_name' in /path/to/foo.php on line xx
因为 self
是静态确定的。
看起来这种事情就是继承的全部意义,所以它至少应该是可能的,即使不是很优雅。 (毕竟这是 PHP。)
我应该做什么?
Say I've got the following:
<?php
abstract class MyParent
{
public static $table_name;
public static get_all(){
return query("SELECT * FROM {$this->table_name}");
}
public static get_all2(){
return query("SELECT * FROM ".self::table_name);
}
}
class Child extends MyParent
{ public static $table_name = 'child'; }
?>
Assuming that query
is correctly defined, neither of these methods does what I want: get_all() throws Fatal error: Using $this when not in object context in /path/to/foo.php on line xx
because $this
is an instance variable.
and get_all2() throws Fatal error: Undefined class constant 'table_name' in /path/to/foo.php on line xx
because self
is statically determined.
It seems like this kind of thing is the whole point of inheritance, so it should be possible at least easily, if not elegantly. (This is PHP after all.)
What should I be doing?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要将
self::table_name
更改为self::$table_name
- 请注意美元符号。但最好的方法是使用 PHP 5.3 的 static 关键字:http ://php.net/manual/en/language.oop5.late-static-bindings.php
self
关键字仅引用 static proparty 定义的类,因此是错误的在这种情况下,因为您需要获取静态属性从父类“继承”。在这种情况下,关键字“static”将解析正确的调用者类并正常工作。You need to change
self::table_name
toself::$table_name
- note the dollar sign. But the best way is to use PHP 5.3's static keyword:http://php.net/manual/en/language.oop5.late-static-bindings.php
The
self
keyword references only the class that static proparty was defined, so it is wrong in this case, as you need to get static property 'inherited' from parent class. The keyword 'static' in this case will resolve correct caller class and work correctly.self::$table_name
,尽管您可能需要static::$table_name
。self::$table_name
, although you probably wantstatic::$table_name
.