I have the following a PHP object with the following properties:
Object:
-Advanced
--Data
To access it in PHP I would have to do the following:
$object->Advanced->Data
Now I want to define a string which has a syntax like this:
$string = "Advanced->Data";
How do I proceed from here to be able to use:
$object->$string = "Something";
So that in the end
$object->Advanced->Data = "Something";
I couldn't figure out using eval or $object->{$string}
If I try to use $object->$string
PHP creates a new property called "Advanced->Data", basically not interpreting the -> Operator.
Though it is a hack, try this, it should work for your case
$arr = array();
$arr['Advanced']['Data'] = 'something';
$string = json_decode(json_encode($arr), 0);
echo $string->Advanced->Data;
Though it is a hack, this can also fetch your desire
$string = &$object->Advanced->Data;
$string = "here we go";
var_dump($object->Advanced->Data);
Probably eval() is not best solution, but it can be useful in your case:
class obj2 {
public $Data = 'test string';
}
class obj1 {
public $Advanced;
public function __construct() {
$this->Advanced = new obj2();
}
}
$test = new obj1();
$string1 = "\$test->Advanced->Data = 'new string';";
$string2 = "\$result = \$test->Advanced->Data;";
eval($string1);
eval($string2);
echo $result . PHP_EOL;
Output will be "new string".
Once try this,
$string = "Advanced->Data";
$arr = explode("->",$string);
$temp = $object->{$arr[0]}->$arr[1];
But this is specific condition. Let me know your requirement if this is not the answer.
Related
Is it possible to create a variable variable pointing to an array or to nested objects? The php docs specifically say you cannot point to SuperGlobals but its unclear (to me at least) if this applies to arrays in general.
Here is my try at the array var var.
// Array Example
$arrayTest = array('value0', 'value1');
${arrayVarTest} = 'arrayTest[1]';
// This returns the correct 'value1'
echo $arrayTest[1];
// This returns null
echo ${$arrayVarTest};
Here is some simple code to show what I mean by object var var.
${OBJVarVar} = 'classObj->obj';
// This should return the values of $classObj->obj but it will return null
var_dump(${$OBJVarVar});
Am I missing something obvious here?
Array element approach:
Extract array name from the string and store it in $arrayName.
Extract array index from the string and store it in $arrayIndex.
Parse them correctly instead of as a whole.
The code:
$arrayTest = array('value0', 'value1');
$variableArrayElement = 'arrayTest[1]';
$arrayName = substr($variableArrayElement,0,strpos($variableArrayElement,'['));
$arrayIndex = preg_replace('/[^\d\s]/', '',$variableArrayElement);
// This returns the correct 'value1'
echo ${$arrayName}[$arrayIndex];
Object properties approach:
Explode the string containing the class and property you want to access by its delimiter (->).
Assign those two variables to $class and $property.
Parse them separately instead of as a whole on var_dump()
The code:
$variableObjectProperty = "classObj->obj";
list($class,$property) = explode("->",$variableObjectProperty);
// This now return the values of $classObj->obj
var_dump(${$class}->{$property});
It works!
Use = & to assign by reference:
$arrayTest = array('value0', 'value1');
$arrayVarTest = &$arrayTest[1];
$arrayTest[1] = 'newvalue1'; // to test if it's really passed by reference
print $arrayVarTest;
In echo $arrayTest[1]; the vars name is $arrayTest with an array index of 1, and not $arrayTest[1]. The brackets are PHP "keywords". Same with the method notation and the -> operator. So you'll need to split up.
// bla[1]
$arr = 'bla';
$idx = 1;
echo $arr[$idx];
// foo->bar
$obj = 'foo';
$method = 'bar';
echo $obj->$method;
What you want to do sounds more like evaluating PHP code (eval()). But remember: eval is evil. ;-)
Nope you can't do that. You can only do that with variable, object and function names.
Example:
$objvar = 'classObj';
var_dump(${$OBJVarVar}->var);
Alternatives can be via eval() or by doing pre-processing.
$arrayTest = array('value0', 'value1');
$arrayVarTest = 'arrayTest[1]';
echo eval('return $'.$arrayVarTest.';');
eval('echo $'.$arrayVarTest.';');
That is if you're very sure of what's going to be the input.
By pre-processing:
function varvar($str){
if(strpos($str,'->') !== false){
$parts = explode('->',$str);
global ${$parts[0]};
return $parts[0]->$parts[1];
}elseif(strpos($str,'[') !== false && strpos($str,']') !== false){
$parts = explode('[',$str);
global ${$parts[0]};
$parts[1] = substr($parts[1],0,strlen($parts[1])-1);
return ${$parts[0]}[$parts[1]];
}else{
return false;
}
}
$arrayTest = array('value0', 'value1');
$test = 'arrayTest[1]';
echo varvar($test);
there is a dynamic approach for to many nested levels:
$attrs = ['level1', 'levelt', 'level3',...];
$finalAttr = $myObject;
foreach ($attrs as $attr) {
$finalAttr = $finalAttr->$attr;
}
return $finalAttr;
How can I call functions on PHP using eval()? is it possible?
I wanna do something like this
<?php
$function1 = 'echo';
$function2 = 'implode';
$arr = array('arg1', 'arg2');
eval("$function1 ($function2(', ', $arr));");
?>
Or call other functions with multiple params?
Is eval() what I'm looking for?
Many thanks!
You don't need to eval anything:
$function1 = 'print';
$function2 = 'implode';
$arr = array('arg1', 'arg2');
$function1($function2(', ', $arr));
In fact, you can even use variable, variables:
$foo = 'print';
$bar = 'foo';
$$bar('hello');
I read php document and I saw this:
class foo{
var $bar = 'I am a bar';
}
$foo = new foo();
$identity = 'bar';
echo "{$foo->$identity}";
And I saw somebody wrote like this:
if (!isset($ns->job_{$this->id})){
//do something
}
But when I tried with this code, It didn't work:
$id1 = 10;
$no = 1;
echo ${id.$no};
Can you guys tell me why it didn't work and when I can use braces with variable correctly?
Live example
Brackets can be used on object types, for instance, to simulate a array index. Supposing that $arr is an array type and $obj an object, we have:
$arr['index'] ===
$obj->{'index'}
You can make it more fun, for instance:
$arr["index{$id}"] ===
$obj->{"index{$id}"}
Even more:
$arr[count($list)] ===
$obj->{count($list)}
Edit: Your problem --
variable of variable
// Your problem
$id1 = 10;
$no = 1;
$full = "id{$no}";
var_dump($$full); // yeap! $$ instead of $
What are you expecting?
$id = 10;
$no = 1;
echo "${id}.${no}"; // prints "10.1"
I'm having some issues with the StdClass() object in PHP..
I'm using it to send information (a string and boolean) to a function.
Outside the function, it works great.
$args = new StdClass();
$args->str = "hej";
$args->ic = TRUE;
fun($arg);
This is then the function called:
function fun($args) {
$str = $args->str;
$ignore_case = $args->ic;
echo $str;
echo $ignore_case;
}
which just writes "stric" instead of the variable contents.
Is there a way to use StdClass to transfer this data and read it correctly?
//Martin
function fun($args) {
$str = $args->str;
$ignore_case = $args->ic;
echo $str;
echo $ignore_case;
}
add $ and second echo should be $ignore_case - I believe
$args = new StdClass();
$args->str = "hej";
$args->ic = TRUE;
fun($arg);
Where is $arg defined? Your call should be fun($args).
You forgot the $ before the variable names in your echos.
echo $str;
echo $ignore_case;
Also, fun($arg); should be fun($args);
I'm having a little struggle on this one and would appreciate some help.
In PHP variable variables can easily be defined like this
$a = "myVar";
$$a = "some Text";
print $myVar; //you get "some Text"
Now, how do I do that in a OOP enviroment? I tried this:
$a = "myVar";
$myObject->$a = "some Text"; //I must be doing something wrong here
print $myObject->myVar; //because this is not working as expected
I also tried $myObject->{$a} = "some Text" but it's not working either. So I must be very mistaken somewhere.
Thanks for any help!
This works for me:
class foo {
var $myvar = 'stackover';
}
$a = 'myvar';
$myObject = new foo();
$myObject->$a .= 'flow';
echo $myObject->$a; // prints stackoverflow
This should work
class foo {
var $myvar = 'stackover';
}
$a = 'myvar';
$myObject = new foo();
$myObject->$a = 'some text';
echo $myObject->myvar;