Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/292.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 我可以用更简洁的方式重写多变量赋值吗?_Php_Arrays_List_Variable Assignment_Php 5.5 - Fatal编程技术网

Php 我可以用更简洁的方式重写多变量赋值吗?

Php 我可以用更简洁的方式重写多变量赋值吗?,php,arrays,list,variable-assignment,php-5.5,Php,Arrays,List,Variable Assignment,Php 5.5,我有11行代码将一个类中的各种类成员变量保存到临时变量中,然后再将它们用于其他事情,例如: // Save parts of myclass $dutyp1 = $this->myclass->p1; $dutyp2 = $this->myclass->p2; ... $dutySg = $this->myclass->sg; // restore parts of myclass $this->myclass->p1 = $dutyp1; $t

我有11行代码将一个类中的各种类成员变量保存到临时变量中,然后再将它们用于其他事情,例如:

// Save parts of myclass
$dutyp1 = $this->myclass->p1;
$dutyp2 = $this->myclass->p2;
...
$dutySg = $this->myclass->sg;
// restore parts of myclass
$this->myclass->p1 = $dutyp1;
$this->myclass->p2 = $dutyp2;
...
$this->myclass->sg = $dutySg;

覆盖类变量的一些代码发生在上述块之后,然后我将变量恢复回类中,如下所示:

// Save parts of myclass
$dutyp1 = $this->myclass->p1;
$dutyp2 = $this->myclass->p2;
...
$dutySg = $this->myclass->sg;
// restore parts of myclass
$this->myclass->p1 = $dutyp1;
$this->myclass->p2 = $dutyp2;
...
$this->myclass->sg = $dutySg;
我应该注意,类中还有其他变量,但只有上面的特定变量才是我要保存/恢复的

问题——是否有一种更简洁的方法来实现这一点,而不是使用多个变量(如
$dutyp1
$dutyp2
,等等),或者我的方法基本上就是这么做的?我不是在寻找疯狂的压缩/编码,而是寻找一种更紧凑的方式来做同样的事情,而不必跨越总共22行来保存/还原。

1:提取(前缀)变量的属性 该函数允许您将所有属性提取到变量

// Without prefix
extract((array) $this->myclass);
// $p1, $p2, etc

// With prefix
extract((array) $this->myclass, EXTR_PREFIX_ALL, 'duty');
// $dutyp1, $dutyp2, etc
要还原变量,您可以使用它的反面。不幸的是,它无法处理您使用的前缀


2:通过引用传递的对象 如果通过引用(
&
)传递对象,修改将实际应用于原始对象

$tmp = &$this->myclass;
$tmp->p1 = 123;

$this->myclass->p1; // 123
这样,您的对象始终是最新的,您无需还原。

提出了以下建议:

//class member names
$keys = array('p1', 'p2', 'sg');

//save
$save = array();
foreach ($keys as $key) $save[$key] = $this->spec->{$key};

//restore
foreach ($keys as $key) $this->spec->{$key} = $save[$key];

您首先使用“临时”变量的原因/逻辑是什么?我正在处理由其他人编写的遗留代码库,这就是他们拥有的代码。我认为逻辑是被保存的数据集是“主数据集”,在计算非主数据集的过程中,它会被其他函数多次覆盖。当计算完成时,需要保证类数据与以前一样,因此数据会被还原。“一些覆盖类变量的代码……然后我将变量还原回类中。”。您并没有在类中真正“存储”变量或数据。数据(对象)被设置(实例化)为类外部的变量或数组,这样类就可以用于不同的数据。如果您需要通过一个类进行一些数据设置,然后将其实例化为一个变量,然后当您需要不同的数据时,将该类实例化为另一个变量。(我对课程的知识不是最渊博的,但这听起来似乎是错误的)嗯,这很酷,不知道这可以做到,谢谢@丹尼斯稍微修改了我的答案,以防有人(有相同的问题)遇到这样的问题:)