2016-11-20 73 views
0

我想在PHP中實現一個數據表,這將是一個基本表中包含就像一個SQL表中的數據,並進行陣列的價值()無法訪問受保護的靜態變量PHP 7.0.13

爲遵循的類定義:

class DataTable{ 

      protected static $tabela; // table 
      //columns and strips, each column point to a strip 
      public function __construct($colunas, $faixas) { 

       $this->tabela = array(); 
       $this->constroiDt($colunas, $faixas); //builds the table 

      } 

      public function getRows($where){ 
       // todo 
      } 

      public static function getTabela(){ 
       return $this->tabela; 
      } 

      private function constroiDt($colunas, $faixas){ 
       if(count($colunas)!= count($faixas)){ 
        $this->tabela = null; 
        return; 
       } 

       $i=0; 
       foreach($colunas as $cl){ 
        $this->tabela = array_merge($this->tabela, array($cl => $faixas[$i])); 
        $i += $i + 1; 
       } 
       // the result will be an array like ('col1' => ('val1','val2'), 'col2' => ('val1','val2')) 
       // if I want to access a value, just type array['col1'][0] for example 

      } 
     } 

外班的功能,當我創建一個例子DT和嘗試訪問它,它似乎將工作:

$columns = array("name", "age"); 
$strips = array(array("someone","another person"),array("20","30")); 
$dt1 = new DataTable($columns, $strips); 
var_dump($dt1); // will print: 
// object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["nome"]=> array(2) { [0]=> string(6) "fulano" [1]=> string(7) "ciclano" } ["idade"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } } 

但後來我加echo "--- " . $dt1::getTabela()['nome'][0];

,它甚至沒有打印---var_dump($dt1::getTabela())var_dump($dt1->getTabela())也是空白。這裏錯過了什麼?也試過this,但沒有奏效。

回答

5

您不應該在靜態函數中使用$this /用於靜態屬性,因爲不一定要使用對象上下文。

取而代之,您應該使用各處的self::$tabela

或者你的變量(和相關方法...)更改爲「正常」的保護特性:

protected $tabela; 
1

你混合靜態變量與非靜態accesors

我只是把你的代碼和我得到了很多的錯誤/通知

NOTICE Accessing static property DataTable::$tabela as non static on line number 10 

NOTICE Accessing static property DataTable::$tabela as non static on line number 31 

NOTICE Accessing static property DataTable::$tabela as non static on line number 31 

NOTICE Accessing static property DataTable::$tabela as non static on line number 31 

NOTICE Accessing static property DataTable::$tabela as non static on line number 31 
object(DataTable)#1 (1) { ["tabela"]=> array(2) { ["name"]=> array(2) { [0]=> string(7) "someone" [1]=> string(14) "another person" } ["age"]=> array(2) { [0]=> string(2) "20" [1]=> string(2) "30" } } } 
FATAL ERROR Uncaught Error: Using $this when not in object context in /home/phptest/public_html/code.php70(5) : eval()'d code:20 Stack trace: #0 /home/phptest/public_html/code.php70(5) : eval()'d code(44): DataTable::getTabela() #1 /home/phptest/public_html/code.php70(5): eval() #2 {main} thrown on line number 20 
+0

謝謝,我改變它沒有靜態和工作 – Fabiotk