如何在php中动态取消类成员变量数组值的设置


how to unset array value of class member variable in php dynamically

我想取消设置类的成员数组变量的第一个值,但无法:

<?php
class A
{
    public  function fun()
    {       
        $this->arr[0] = "hello";
    }
    public $arr;
}

$a = new A();
$a->fun();
$var ="arr";
unset($a->$var[0]);  //does not unset "hello" value
print_r($a);

我在谷歌搜索后找不到任何解决方案。如何动态删除第一个值?

尝试以下操作:

unset($a->{$var}[0]);

代码的问题是,PHP试图访问成员变量$var[0](即null(,而不是$var

您可以尝试使用array_shift:

array_shift($a->{$var});

此函数使用对值的引用,并从数组的开头移除(和返回(值。

<?php
  class A
 {
   public  function fun()
   {       
      $this->arr[0] = "hello";
   }
   public $arr;
}

 $a = new A();
 $a->fun();
 // no need to take $var here 
 // you can directly access $arr property wihth object of class
 /*$var ="arr";*/
 // check the difference here  
 unset($a->arr[0]);  //unset "hello" value
 print_r($a);
?>

尝试此

由于$arr是类a的成员并声明为public,因此可以直接使用

$a = new A();
$a->fun();
unset $a->arr[0];

但您会感到惊讶的是,对于数字索引数组,取消设置可能会带来问题。

假设你的数组是这样的;

$arr = ["zero","one","two","three","four"];
unset($arr[2]);       // now you removed "two"
echo $arr[3];         // echoes three

现在数组是["零"、"一"、未定义、"三"、"四"];

$arr[2]不存在,它是未定义的,其余的没有重新索引。。。

对于数字索引数组,使用以下方法更好:

$arr = ["zero","one","two","three","four"];
array_splice($arr,2,1);  // now you removed "two" and reindexed the array 
echo $arr[3];            // echoes four...

现在数组是["零"、"一"、"三"、"四"];