PHP致命错误:无法访问空属性

Bis*_*han 62 php fatal-error

我是新手php,我已执行下面的代码.

<?php
class my_class{

    var $my_value = array();
    function my_class ($value){
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->$my_value = $value;

    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c');
$a->my_class('d');

foreach ($a->my_value as &$value) {
    echo $value;
}

?>
Run Code Online (Sandbox Code Playgroud)

我得到了以下错误.可能是什么错误?

Notice: Undefined variable: my_value in C:\xampp\htdocs\MyTestPages\f.php on line 15

Fatal error: Cannot access empty property in C:\xampp\htdocs\MyTestPages\f.php on line 15
Run Code Online (Sandbox Code Playgroud)

Phi*_*ipp 174

您以错误的方式访问该属性.使用$this->$my_value = ..语法,您可以使用$ my_value中的值的名称设置该属性.你想要的是什么$this->my_value = ..

$var = "my_value";
$this->$var = "test";
Run Code Online (Sandbox Code Playgroud)

是相同的

$this->my_value = "test";
Run Code Online (Sandbox Code Playgroud)

要修复示例中的一些内容,下面的代码是更好的方法

class my_class {

    public  $my_value = array();

    function __construct ($value) {
        $this->my_value[] = $value;
    }

    function set_value ($value) {
        if (!is_array($value)) {
            throw new Exception("Illegal argument");
        }

        $this->my_value = $value;
    }

    function add_value($value) {
        $this->my_value = $value;
    }
}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->add_value('c');
$a->set_value(array('d'));
Run Code Online (Sandbox Code Playgroud)

这可以确保my_value在调用set_value时不会将其类型更改为字符串或其他内容.但你仍然可以直接设置my_value的值,因为它是公开的.最后一步是,使my_value变为私有,并且只能通过getter/setter方法访问my_value


Mar*_*o D 30

首先,不要使用var声明变量,但是

public $my_value;
Run Code Online (Sandbox Code Playgroud)

然后你可以使用它来访问它

$this->my_value;
Run Code Online (Sandbox Code Playgroud)

并不是

$this->$my_value;
Run Code Online (Sandbox Code Playgroud)


Val*_*Val 10

要访问类中的变量,必须使用$this->myVar而不是$this->$myvar.

并且,您应该使用访问标识符来声明变量而不是var.

请在这里阅读文档.


Abu*_*sae 5

正如我在您的代码中看到的那样,您似乎正在遵循基于PHP4的基于PHP的OOP的旧文档/教程(OOP不受支持,但以某种方式适应以简单的方式使用),因为PHP5添加了官方支持并且符号已经改变了.

请在此处查看此代码评论:

<?php
class my_class{

    public $my_value = array();

    function __construct( $value ) { // the constructor name is __construct instead of the class name
        $this->my_value[] = $value;
    }
    function set_value ($value){
    // Error occurred from here as Undefined variable: my_value
        $this->my_value = $value; // remove the $ sign
    }

}

$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string 
// $a->my_class('d'); // you can call this if you mean calling the contructor 


// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
    echo $value;
}

?>
Run Code Online (Sandbox Code Playgroud)

我希望它有所帮助