功能改变和返回对象的价值,即使它是按值传递的'

时间:2015-12-25 15:17:57

标签: php

我处于这样一种情况,即我将数组映射到对象,然后将其分配给另一个数组。只需从嵌套数组中创建一个对象数组。

array (size=2)
  0 => 
    array (size=3)
      'edu_id' => string '3' (length=1)
      'edu_degree' => string 'MCA' (length=3)
      'edu_institute' => string 'ECB' (length=3)
  1 => 
    array (size=3)
      'edu_id' => string '4' (length=1)
      'edu_degree' => string 'BCA' (length=3)
      'edu_institute' => string 'CET' (length=3)

这是数组,我试图将其转换为 -

array (size=2)
  0 => 
    object(MatEducation)[11]
      private 'id' => int 1
      private 'eduId' => string '3' (length=1)
      private 'degree' => string 'MCA' (length=3)
      private 'institute' => string 'ECB' (length=3)
  1 => 
    object(MatEducation)[11]
      private 'id' => int 1
      private 'eduId' => string '4' (length=1)
      private 'degree' => string 'BCA' (length=3)
      private 'institute' => string 'CET' (length=3)

这是mapper函数。

/**
     * @param MatEducation $obj - i am passing this object so that
     * function dont need to create 'new' object every time.if i create
     * a new object then i get the desired result.
     * @param array $arr this array contain the value to be converted.
     * @return MatEducation
     */
    public function toMatEducation(MatEducation $obj, array $arr)
    {
        $obj->setEduId($arr['edu_id']);
        $obj->setDegree($arr['edu_degree']);
        $obj->setInstitute($arr['edu_institute']);
        return $obj;
    }

对mapper函数的调用就像 -

/**return array of MatEducation Objects.*/
$arrayOfObject = array();
foreach ($result as $key=>$row) {
    $arrayOfObject[$key] = $this->map->toMatEducation($education, $result[$key]);
}
return $arrayOfObject;

因为默认情况下传递的所有值都是按值传递的。因此$education对象不得更改,并应从函数返回它的副本。如果它仍然在改变,而不是在分配给$arrayOfObject[$key]时,应该生成新的副本。所以我的问题是为什么$arrayOfObject的所有索引都指向同一个对象。 编辑这是我现在得到的数组。

array (size=2)
  0 => 
    object(MatEducation)[11]
      private 'id' => int 1
      private 'eduId' => string '4' (length=1)
      private 'degree' => string 'BCA' (length=3)
      private 'institute' => string 'CET' (length=3)
  1 => 
    object(MatEducation)[11]
      private 'id' => int 1
      private 'eduId' => string '4' (length=1)
      private 'degree' => string 'BCA' (length=3)
      private 'institute' => string 'CET' (length=3)

1 个答案:

答案 0 :(得分:1)

对象本身是按值传递的,但它们的属性不是。

$a = new stdclass;
$a->p = 0;
$b = $a;
$b->p = 1;

$a->p将更改为0.如果您现在更改$b,则不会影响$a本身,但会更改{{1}的属性会影响$b的属性。虽然它们不是同一个变量,但它们引用同一个对象。

注意:但是对于数组来说并非如此 - 两个不通过引用的变量不会引用同一个数组。例如,$a不会更改$a = [0]; $b = $a; $b[0] = 1;的值,除非它是$a[0],但对象不是这样。

您的案例的简单解决方案是使用$b =& $a。在您的示例中,如果您使用clone代替,则可以使用。