简体   繁体   中英

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

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:

  1. call_user_func
  2. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM