Mike Robinson
Mike Robinson

Reputation: 8965

PHP: how do I know if a variable is a "::class?"

I have PHP code which passes a parameter as User::class which is then instantiated with new $p.

But I also need to be able to pass it a query instance ... a concrete instance of something which, of course, is also an object ... which is a member of a class.

Therefore, how do I detect whether the value of a variable was created using the ::class nomenclature?


A little one-liner suggests an answer:

$ php -r 'class foo {}; print gettype(foo::class);'
string

Is this assumption correct? An object instance (e.g. a query) would be of type object while a ::class construct would be string? Did I just answer my own question?


To clarify, my code wants to do this:

 if (gettype($q) == 'string') {
   $query = new $q();      // must be '::class' (TRUE in my situation tho' not generally)
 } else {                  // (so, the only other possibility in my case is 'object')
   $query = $q;            // existing object instance
 }

... and in my particular situation I know the parameter will always be one or the other. I don't need a generalized solution.

Upvotes: 0

Views: 505

Answers (5)

Amin Shojaei
Amin Shojaei

Reputation: 6538

The foo::class is a string and it's not different from other strings.

The class_exists function may help you:

    var_dump(class_exists(foo::class));

result: true

Upvotes: 2

nerdlyist
nerdlyist

Reputation: 2857

You can shoot for instanceof

if($q instanceof Foo){
    echo "Here do the things you need with your class";
} else {
    echo "Assume it is a string?";
}

The other option I would suggest is to make sure you get the data you expect with type hinting.

function bar(Foo $foo){
    //foo has to be Foo class or exception will be thrown.
}

Upvotes: 0

ryantxr
ryantxr

Reputation: 4217

Here are your options:

class Foo {
}

$foo = new Foo;

is_object($foo); // $foo is an object

is_string($foo); // No, $foo isn't a string

$foo instanceof Foo // $foo is an instance of Foo

is_string(Foo::class) // Foo::class is a string just like any other string

get_class($foo) // returns 'Foo'

class_exists('Foo') // returns true if class Foo can be found

Upvotes: 2

Mike Robinson
Mike Robinson

Reputation: 8965

Absent anyone hurrying up to tell me that I am mistaken, I'm going to say that "yes, for my purposes, I did answer my own question." (I edited the original question to show what I have in mind.)

Upvotes: 0

Captain Hypertext
Captain Hypertext

Reputation: 2506

The foo::class call returns a string of the class name. You could instantiate an object and feed it a variable like so:

$p = foo::class;
$query = new QueryThing();
$obj = new $p($query);

You could do this to see what type of class you have

get_class($p) // returns "foo"
$p instanceof foo // returns true

But you can't know that your object was instantiated dynamically from a foo::class call.

Upvotes: 0

Related Questions