0

所以我有一个问题,我有一个数组传递给 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();
 ?>
4

2 回答 2

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();
于 2013-10-21T02:09:58.657 回答
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();
于 2013-10-21T02:16:41.793 回答