无法访问受保护的静态变量php 7.0.13

时间:2016-11-20 22:47:44

标签: php arrays

我试图在php中实现一个 DataTable 类,它基本上是一个包含数据的表,就像一个sql表一样,将由 array()构成

该课程定义如下:

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,但没有工作。

2 个答案:

答案 0 :(得分:5)

您不应在静态函数/静态属性中使用$this,因为不一定要使用对象上下文。

相反,您应该在任何地方使用self::$tabela

或者将您的变量(和相关方法......)更改为“普通”受保护属性:

protected $tabela;

答案 1 :(得分:1)

您正在将静态变量与非静态加法器混合

我只是把你的代码,我收到了很多错误/通知

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