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);
Related
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.
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;
For example, I have the following:
$ValuePath = "object->data->user_nicename";
And I need to print not the value of the $ValuePath but the value of the $variable->data->user_nicename that is part of a larger call .. as I have the following situation:
echo $objects->$ValuePath->details;
and is not working .. I'm getting the error Class cannot be converted to string or something when I try it like that.
PHP pseudo-code:
function get_by_path($object, $path)
{
$o = $object;
$parts = explode('->', $path);
// if you want to remove the first dummy object-> reference
array_shift($parts);
$l = count($parts);
while ($l)
{
$p = array_shift($parts); $l--;
if ( isset($o->{$p}) ) $o = $o->{$p};
else {$o = null; break;}
}
return $o;
}
Use like this:
$value = get_by_path($obj, "object->data->user_nicename");
// $value = $obj->data->user_nicename;
Check also PHP ArrayAccess Interface which enables to access objects as arrays dynamicaly
NO you cannot do that.
From your declaration $ValuePath is a variable which holds a plain string ('object->data->user_nicename') this string is not an object.
Where as,
$objects->object->data->user_nicename->details is a object.
so $objects->object->data->user_nicename->details is not same as $objects->$ValuePath->details
Let's say I have this:
function data() {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
return $out;
}
I can output the data by declaring it as a variable, then using the array index to echo it:
$data = data();
echo $data['a'];
echo $data['b'];
echo $data['c'];
But, I'm calling functions inline with other functions, and I'm trying to avoid having to declare a variable first. For instance, I want to do something like this:
echo data()[0]; //pulls first value in array without declaring it as a variable first. This needs to be variable i.e. data()[1] data()[2] etc.
Or more specifically, I'm actually trying to do it as a class:
$traverseXML->getData("Route", "incoming", "field", "value")[0]
//getData() returns an array, I'm trying to get a single value.
Personally i would do something like this
<?php
function data($key = false, $default = 'not found') {
$out['a'] = "abc";
$out['b'] = "def";
$out['c'] = "ghi";
if($key)
{
if(isset($out[$key]))
return $out[$key];
else
return $default;
}
else
return 'empty';
}
?>
<?= data('a') ?>
I'm trying to make a PHP function that wraps around a variable that will check the variable value and change it if it matches another variable.
I'm sure I'm doing it wrong, but...
Here's what I have so far:
<?php
function Clear_Value(){
$val='NONE';
if(this== $val){ this=='';}
};
$one = 'One';
$two = 'Two';
$three = 'NONE';
$four = 'Four';
Clear_Value($one);
Clear_Value($two);
Clear_Value($three);
Clear_Value($four);
echo $one.'<br>';
echo $two.'<br>';
echo $three.'<br>';
echo $four.'<br>';
?>
The output I'm going for would be:
One
Two
Four
I hope that's clear. I'm still learning functions in php so any pointers would be great.
Thanks
You need to pass an argument by reference:
function Clear_Value(&$arg){
if ($arg == 'NONE') $arg = '';
}
This way, the function can modify the variable's contents.
Live example: http://ideone.com/igHc5
what your constant this stands for?
you have to create some input variable in your function and use & prefix (refers to variable in memory)
function Clear_Value(&$var){
$val='NONE';
if($var == $val)
$var = '';
};
and another thing, if you want to change value of a variable, you use just single "=". i recommend you to see basics of syntax at php.net
sorry for my english
I am not sure what you expect here.
But when you execute this program it will show undefined variable error.
Try my sample changed code:-
<?php
function Clear_Value($sam){
$val='NONE';
if($sam== $val){ $sam=='';}
echo $sam.'<br>';
};
$one = 'One';
$two = 'Two';
$three = 'NONE';
$four = 'Four';
Clear_Value($one);
Clear_Value($two);
Clear_Value($three);
Clear_Value($four);
/*
echo $one.'<br>';
echo $two.'<br>';
echo $three.'<br>';
echo $four.'<br>';
*/
?>