Gal
Gal

Reputation: 23662

PHP: Check if a variable is an instance of a certain class

Every time I get a variable through $_GET I want to verify that it is indeed an object of the User class.

So:

if (isUser($_GET['valid_user']))
{
...
}

is there a built in function to use instead of this so called "isUser"?

Thanks a lot!

Upvotes: 21

Views: 14342

Answers (5)

Sarfraz
Sarfraz

Reputation: 382909

you could try this:

if (is_object($_GET['valid_user']))
{
     // more code here
}

Upvotes: 2

Pekka
Pekka

Reputation: 449813

You can verify any variable for a certain class:

if ($my_var instanceof classname)

however, in your case that will never work, as $_GET["valid_user"] comes from the request and is never going to be an object.

isUser() is probably a custom function from a user management library that authenticates the current session. You need to take a look how that works if you want to replace it.

Upvotes: 51

user50049
user50049

Reputation:

$_GET[] variables are more constants than variables, they are read only .. but happen to be accessed like you would any other $variable.

In your example:

if (isUser($_GET['valid_user']))
{
...
}

I would hope that it would read:

if (isUser($some_sanatized_variable))

.. unless isUser() is what's doing that. 'Variables' that PHP sets don't belong to any class, which illustrates my concern that isUser() may not adequately know what its dealing with.

Upvotes: 0

miku
miku

Reputation: 188194

There is a function in the PHP language, which might help you:

bool is_a ( object $object , string $class_name )

From the documentation: Checks if the object is of this class or has this class as one of its parents

Upvotes: 6

dfilkovi
dfilkovi

Reputation: 3091

is_object to check if it is a object and link below explains how to check which class

http://hr.php.net/manual/en/reflectionclass.isinstance.php

Upvotes: 0

Related Questions