问题
I am wondering if there is something similar to javascript or VB's with
statement but in php
The way this works, for example in VB is shown below. The two code snippets do the same effect:
array[index].attr1 = val1;
array[index].attr2 = val2;
array[index].attr3 = val3;
is equal to :
With(array[index])
.attr1 = val1
.attr2 = val2
.attr3 = val3
End With
回答1:
Not exactly the with statement, but you can use references in your example:
$r = &$array[index];
$r->attr1 = val1;
$r->attr2 = val2;
$r->attr3 = val3;
回答2:
If needed with arrays as in your example, you can mimic the with statement
by using the array_merge function:
$array = array(
'index' => array(
'attr1' => 'val1',
'attr2' => 'val2',
'attr3' => 'val3'
)
);
var_dump( $array );
$array['index'] = array_merge(
$array['index'],
array(
'attr1' => 'newval1',
'attr4' => 'newval4'
)
);
var_dump( $array );
Output:
array
'index' =>
array
'attr1' => string 'val1' (length=4)
'attr2' => string 'val2' (length=4)
'attr3' => string 'val3' (length=4)
array
'index' =>
array
'attr1' => string 'newval1' (length=7)
'attr2' => string 'val2' (length=4)
'attr3' => string 'val3' (length=4)
'attr4' => string 'newval4' (length=7)
来源:https://stackoverflow.com/questions/8109178/with-statement-in-php