PHP致命错误:无法访问空属性 [英] PHP Fatal error: Cannot access empty property
问题描述
我是php
的新手,我已经执行了以下代码.
I'm new to php
and I have executed below code.
<?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;
}
?>
我遇到了以下错误.可能是什么错误?
I got below errors. What could be the error?
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
推荐答案
您以错误的方式访问属性.使用$this->$my_value = ..
语法,可以使用$ my_value中的值名称设置属性.您想要的是$this->my_value = ..
You access the property in the wrong way. With the $this->$my_value = ..
syntax, you set the property with the name of the value in $my_value. What you want is $this->my_value = ..
$var = "my_value";
$this->$var = "test";
与
$this->my_value = "test";
要解决示例中的一些问题,下面的代码是一种更好的方法
To fix a few things from your example, the code below is a better aproach
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'));
这确保my_value不会在调用set_value时将其类型更改为字符串或其他类型.但是您仍然可以直接设置my_value的值,因为它是公共的.最后一步是将my_value设为私有,并且仅通过getter/setter方法访问my_value
This ensures, that my_value won't change it's type to string or something else when you call set_value. But you can still set the value of my_value direct, because it's public. The final step is, to make my_value private and only access my_value over getter/setter methods
这篇关于PHP致命错误:无法访问空属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!