[英]How to access var from parent class inside a static function
How do I access the vars from the parents class inside a static class/function? 如何在静态类/函数中从父类访问var?
(still a noob when it comes to oop and php ;-)) (oop和php还是一个菜鸟;-))
Small example 小例子
class database{
public $dbTable = 'mysqltable';
}
class install extends database{
public static function getTable(){
$this->dbTable;// not working
self::dbTable;// not working
}
}
Use parent:: and make sure your variable from your extending class is also defined as static . 使用parent ::并确保扩展类中的变量也定义为static 。
Following should work: 以下应该工作:
class database{
public static $dbTable = 'mysqltable';
}
class install extends database{
public static function getTable(){
parent::$dbTable;// working
}
}
Accessing instance variables from static methods isn't supported in PHP. PHP不支持从静态方法访问实例变量。
If you make $dbTable static (change public $dbTable = 'mysqltable';
to public static $dbTable = 'mysqltable';
), you'll be able to access it from your static getTable() method like this: parent::$dbTable;
如果将$ dbTable设为静态(将
public $dbTable = 'mysqltable';
更改为public static $dbTable = 'mysqltable';
),则可以从静态getTable()方法访问它,如下所示: parent::$dbTable;
. 。
You need to make the property static to access it form a static method. 您需要将属性设为静态,以通过静态方法访问它。 $this is not available from static methods.
$ this在静态方法中不可用。 If you do that, you can access the static method via self or parent:
如果这样做,则可以通过self或parent访问静态方法:
class database
{
public static $dbTable = 'mysqltable';
}
class install extends database
{
public static function getTable()
{
return array(self::$dbTable, parent::$dbTable);
}
}
var_dump(install::getTable());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.