PHP使用代码获取“未定义变量和”空属性“错误

时间:2011-06-20 21:18:33

标签: php

  

可能重复:
  PHP: “Notice: Undefined variable” and “Notice: Undefined index”

我已将此错误减少到最小的代码量,并且它非常小,我真的觉得这里很蠢。

我有2个文件class1.php:

  1 <?php
  2 class insertText{
  3         //properties
  4         protected $paragraph1='<p>this is a test paragraph</p>';
  5         protected $bigHeader='<h1>header1</h>';
  6         protected $textArray;
  7
  8         public function __construct () {
  9                 $this->$textArray = array($this->$bigHeader1, $this->$paragraph1);
 10         }
 11         public function getText(){
 12                 return $this->$textArray;
 13         }
 14 }
 15 ?>

和test.php:

1 <?php
2 include './class1.php';
3 echo "Begin\n";
4
5 $filler = new insertText();
6 echo $filler->getText();
7
8 echo "end\n";
9 ?>

当我跑步时:     $ php text.php

Begin
PHP Notice:  Undefined variable: bigHeader1 in class1.php on line 9
PHP Fatal error:  Cannot access empty property in class1.php on line 9

我知道这是一个简单的答案,我搜索并搜索每个帖子都有错误信息。我甚至尝试将文本的赋值移动到构造函数中的变量中,并且它无法正常工作。

1 个答案:

答案 0 :(得分:5)

您需要使用:

$this->textArray = array($this->bigHeader1, $this->paragraph1);

...而不是..

$this->$textArray = array($this->$bigHeader1, $this->$paragraph1);

即:$this->$bigHeader1中的第二个美元符号是多余的。 (您实际上是在尝试访问将在$bigHeader1变量中定义的类元素,而不是类实例变量本身。)