开发者

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

开发者 https://www.devze.com 2022-12-11 18:07 出处:网络
Every time I get a variable through $_GET I want to verify that it is indeed an object of the User 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!


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.


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


you could try this:

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


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


$_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.

0

精彩评论

暂无评论...
验证码 换一张
取 消