简体   繁体   中英

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?

(still a noob when it comes to oop and 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 .

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.

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; .

You need to make the property static to access it form a static method. $this is not available from static methods. If you do that, you can access the static method via self or 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM