所以我有一个问题我有一个传递给setData函数的数组 之后我调用getE来假设返回数组但是我得到Null我做错了什么?
<?php
class Se {
public $data1;
public function setData(array $data){
if (empty($data)) {
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
}
public function getE(){
return $data1[0];
}
}
$tmpaaa= array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
所以我修改后的代码现在看起来像这样
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = $data;
}
public function getE()
{
return $this->$data1[0];
}
};
$tmpaaa= array('3','2');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();
?>
答案 0 :(得分:3)
为了从类中访问类实例属性,您需要在变量名前加$this
。见http://php.net/manual/language.oop5.properties.php
要解决您的问题,请在setData
$data1 = $data;
$data1 = array_values($data1);
var_dump($data1);
到这个
$this->data1 = array_values($data);
var_dump($this->data1);
和getE
到
public function getE(){
return $this->data1[0];
}
因为$data1
中需要Se
属性,我会在构造函数中设置它,例如
public function __construct(array $data) {
$this->setData($data);
}
并使用
实例化它$ttt = new Se($tmpaaa);
echo $ttt->getE();
答案 1 :(得分:1)
还建议不要关闭类文件中的php标记,这样可以防止空间问题。
<?php
class Se {
public $data1;
public function setData(array $data)
{
if (empty($data))
{
throw new InvalidArgumentException('The name of an employee cannot be empty.');
}
$this->data1 = array_values($data); //you error was here, no need to to assign $data twice so I deleted top line.
}
public function getE()
{
return $this->data1[0];
}
}
$tmpaaa = array('3333','222');
$ttt = new Se();
$ttt->setData($tmpaaa);
echo $ttt->getE();