Anna K.
Anna K.

Reputation: 1995

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:)

Upvotes: 0

Views: 276

Answers (3)

Andreas Linden
Andreas Linden

Reputation: 12721

you can do the following

$ref = ltrim($var, '$');
get_class($ref);

Upvotes: 1

kitti
kitti

Reputation: 14834

Try using variable variables: http://php.net/manual/en/language.variables.variable.php

Something like:

$var = 'object';
$class = get_class( $$var );

Upvotes: 1

nico
nico

Reputation: 1138

you can do

$var = new $object();

Upvotes: 1

Related Questions