通过类实例进行PhP foreach

时间:2018-10-31 15:40:49

标签: php object foreach

我想知道这个奇怪的事情:

public function getAllCustomers()
{
    $customers = $this->redis->keys("customer:*");
    foreach ($customers as $value) {
        return new \Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"id"),$this->redis->hget($value,"email"));
    }
}

此方法从我的数据库返回所有客户。

但是,如果我尝试遍历所有这些客户:

foreach ($customerController->getAllCustomers() as $customer) {
    var_dump($customer);
}

找不到getName()方法。 var_dump返回:

NULL
NULL
NULL

客户类别:

class Customer {
    var $name;
    var $id;
    var $email;

    function __construct($name, $id,$email) {
        $this->name = $name;
        $this->id = $id;
        $this->email = $email;
    }

     /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
    */
    public function getEmail()
    {
        return $this->email;
    }

    public function __toString()
    {
       return "";
    }
}

我对PHP还是陌生的,不理解为什么我无法访问“客户”对象的字段。

2 个答案:

答案 0 :(得分:2)

您的问题:您不会返回一组客户,而只会返回一个客户。由于您的函数仅返回 1 对象->而在PHP中,对对象使用foreach循环时,您得到了他的字段->而字段 >具有getName功能。

解决方案:初始化客户数组,填充并从函数中返回。

 public function getAllCustomers()
{
    $customers = $this->redis->keys("customer:*");
    $customersObjs = array();
    foreach ($customers as $value) {
        $customersObjs[] = new Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"id"),$this->redis->hget($value,"email")));
    }
    return $customersObjs;
}

现在,您可以循环使用customersObjs的数组了:

foreach ($customerController->getAllCustomers() as $customer) {
    echo $customer->getName();
}

答案 1 :(得分:1)

解决方案:

public function getAllCustomers()
{
    $customers = $this->redis->keys("customer:*");
    $custumersArray = array();
    foreach ($customers as $value) {
        $custumersArray[] = \Customer($this->redis->hget($value,"name"),$this->redis->hget($value,"email"),$this->redis->hget($value,"id"));
    }
    return $custumersArray;
}

问题是您返回的是单个数组,而不是数组列表。