How do I call a Class->Method from strings? - php

It it possible to call a class and method from strings?
Something like:
// $_REQUEST['var'] = 'House-Kitchen';
$var = explode('-',$_REQUEST['var']);
echo $var[0]->$var[1];

Yes. its possible. If $var[0] is the name of class then following will work.
call_user_func(array($var[0], $var[1]));
If $var[0] is the name of class instance then following will work.
call_user_func(array(get_class(${$var[0]}), $var[1]));
Links:
call_user_func
get_class

The better way is to try.
I did try :
$House = new stdClass();
$House->Kitchen = "visible result";
$_REQUEST['var'] = 'House-Kitchen';
$var = explode('-',$_REQUEST['var']);
echo $$var[0]->$var[1];
It works. Be careful : you need to use double $ for the first element (to use variable with $var[0] name).
And be very careful : it's a high security breach (you allow everyone to call methods on current defined class).

Related

Laravel Quick Question : $data->Day(variable here) how to use variable on this? [duplicate]

How can i reference a class property knowing only a string?
class Foo
{
public $bar;
public function TestFoobar()
{
$this->foobar('bar');
}
public function foobar($string)
{
echo $this->$$string; //doesn't work
}
}
what is the correct way to eval the string?
You only need to use one $ when referencing an object's member variable using a string variable.
echo $this->$string;
If you want to use a property value for obtaining the name of a property, you need to use "{" brackets:
$this->{$this->myvar} = $value;
Even if they're objects, they work:
$this->{$this->myobjname}->somemethod();
As the others have mentioned, $this->$string should do the trick.
However, this
$this->$$string;
will actually evaluate string, and evaluate again the result of that.
$foo = 'bar';
$bar = 'foobar';
echo $$foo; //-> $'bar' -> 'foobar'
you were very close. you just added 1 extra $ sign.
public function foobar($string)
{
echo $this->$string; //will work
}
echo $this->$string; //should work
You only need $$string when accessing a local variable having only its name stored in a string. Since normally in a class you access it like $obj->property, you only need to add one $.
To remember the exact syntax, take in mind that you use a $ more than you normally use. As you use $object->property to access an object property, then the dynamic access is done with $object->$property_name.

Determine class of an object

It know it can be done with get_class($variable).
The problem is that my $object is actually a string containing the variable name.
so:
$object = new MyClass();
$var = '$object';
$class = get_class($var); // obviously fails
I can't use get_class($object), because I don't have direct access to that variable (I'm producing the $var string from parsing a PHP expression using token_get_all())
I tried using eval(sprintf('return get_class(%s);', $var)), but it doesn't work because the variable appear undefined from eval's scope :(
Is there a way to do this?
I need to know the class in order to pass it to ReflectionMethod, so I can get information about a method (the next element in the PHP expression).
NVM: I'm pretty sure it is not possible. Sorry for asking:)
you can do
$var = new $object();
Try using variable variables: http://php.net/manual/en/language.variables.variable.php
Something like:
$var = 'object';
$class = get_class( $$var );
you can do the following
$ref = ltrim($var, '$');
get_class($ref);

Call function from an object?

<?php
$ar = (object) array('a'=>function(){
echo 'TEST';
});
$ar->a();
?>
I get this error Call to undefined method
Update:
If you are using PHP 5.3 or greater, take a look at other answers please :)
I don't think that's correct syntax, it would give you:
Parse error: syntax error, unexpected T_FUNCTION in....
You need to create a class, add method to it, use new keyword to instantiate it and then you will be able to do:
$ar->a();
class myclass
{
public function a()
{
echo 'TEST';
}
}
$ar = new myclass;
$ar->a(); // TEST
See Classes and Objects for more information.
Anonymous or not, you have a callback function, thus you need to handle it as such. E.g.:
<?php
$ar = (object) array(
'a' => function(){
echo 'TEST';
}
);
call_user_func($ar->a);
?>
For some reason it doesn't seem possibly to run the closure the way you do.
If you modify your code and set another variable to the function, it can be called:
$ar = (object) array('a'=>function(){
echo 'TEST';
});
$a = $ar->a;
$a();
This is no solution. But from what I can see, this seems like a bug or limitation in PHP 5.3.
I am using 5.3.5 when trying this.
There is no function a() but the property a, so you should call it by $ar->a.
Anyway I don't think it's going to work the way you expect it to.
EDIT:
As suggested by Álvaro G. Vicario you should use call_user_func, not echo to call the function and it will work correctly.
Or, just for the fun of it, you can do something like this -
<?php
$ar = new stdClass;
$ar->a = function($to_echo){ echo $to_echo; };
$temp = $ar->a;
//[Edit] - $ar->a("hello"); // doesn't work! php tries to match an instance method called "func" that is not defined in the original class' signature
$temp("Hey there");
call_user_func($ar->a("You still there?"));
?>

php object : get value of attribute by computed name

How do I access an attribute of an object by name, if I compute the name at runtime?
For instance. I loop over keys and want to get each value of the attributes "field_" . $key.
In python there is getattribute(myobject, attrname).
It works, of course, with eval("$val=$myobject->".$myattr.";");
but IMO this is ugly - is there a cleaner way to do it?
Keep always in mind that a very powerful feature of PHP is its Variable Variables
You can use
$attr = 'field' . $key;
$myobject->$attr;
or more concisely, using curl brackets
$myobject->{'field_'.$key};
$myobject->{'field_'.$key}
$val = $myobject->$myattr;
With reflection:
$reflectedObject = new ReflectionObject($myobject);
$reflectedProperty = $reflectedObject->getProperty($attrName);
$value = $reflectedProperty->getValue($myobject);
This works only if the accessed property is public, if it's protected or private an exception will occurr.
I know this is an old subject, but why not just use magic methods?
$myObj->__get($myAttr)

How to get variable name in PHP?

func($name1) should return name1
Is it possible?
Here's a function that does it.
function var_name (&$iVar, &$aDefinedVars)
{
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
Call it like this
$test = "blah";
echo var_name($test, get_defined_vars());
That will print out "test".
I originally found that function over here You can also do it by iterating over the array returned by get_defined_vars(). That might be a bit easier to understand.
No, there is no way to get the name of a variable in PHP.
When calling a function, that function will only receive the content of the variable, and not the "variable itself" -- which means a function cannot find out the name of the variable that was passed to it.
Good Idea ? No
Any usecase you where you should do it ? No
Proof of concept ? Sure !
<?php
a($test);
function a($x) {
$trace = debug_backtrace();
$file = file($trace[0]['file']);
$line = $file[$trace[0]['line']-1];
var_dump($line); // Prints "a($test);" Do the Stringparsing and your done
}
Yes, this takes the "easy" by reading the sourcefile, it is also doable by using a php extension called "bytekit" that gives you userland access to the php opcodes and work from there.
No.
When you define a function, you specify a local variable name for it to have inside the scope of that function. PHP will pass the function the appropriate value, but the symbol is no longer in scope.
You could look into using "variable variables" as an alternative, however.
Obviously, it is possible for sufficiently high values of crazy.
The comments on this page include several techniques:
http://php.net/manual/en/language.variables.php
lucas dot karisny at linuxmail dot org's answer works on my machine:
http://www.php.net/manual/en/language.variables.php#49997
YMMV.

Categories