Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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!

like image 392
Gal Avatar asked Nov 19 '09 13:11

Gal


3 Answers

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.

like image 190
Pekka Avatar answered Oct 22 '22 22:10

Pekka


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

like image 38
miku Avatar answered Oct 22 '22 21:10

miku


you could try this:

if (is_object($_GET['valid_user']))
{
     // more code here
}
like image 37
Sarfraz Avatar answered Oct 22 '22 21:10

Sarfraz