Dennis
Dennis

Reputation: 8111

Can I rewrite multiple variable assignment in a more compact way?

I am have 11 lines of code saving various class member variables from a class into temporary variables, before using them for other things, like so:

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

Some code that overwrites class variables happens after the above block, and then I restore variables back into the class, like so:

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

I should note that there are other variables inside the class but only the above specific variables is what I seek to save/restore.

Question -- is there a more compact way to do this, instead of using up multiple variables (like $dutyp1, $dutyp2, etc), or is what I have pretty much the way to do it? I am not looking for crazy compression/encoding, but a more compact way of doing the same thing without having to span 22 lines total for save/restore.

Upvotes: 2

Views: 78

Answers (2)

Tim S.
Tim S.

Reputation: 13843

1: extract properties to (prefixed) variables

The extract() function allows you to extract all properties to variables.

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

// With prefix
extract((array) $this->myclass, EXTR_PREFIX_ALL, 'duty');
// $dutyp1, $dutyp2, etc

To restore the variables, you can use it’s opposite, compact(). Unfortunately, it can’t handle the prefix you used.


2: Object passed by reference

If an object is passed by reference (&), modifications will actually be applied to the original object.

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

$this->myclass->p1; // 123

This way, your object is always up-to-date and you don’t have to restore.

Upvotes: 2

Dennis
Dennis

Reputation: 8111

Came up with this:

//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];

Upvotes: 0

Related Questions