PHP » PYTHON |
login |
register |
about
|
PYTHON Type Operators
is this article helpful?
|
Python replacement for PHP's Type Operators
[
edit
| history
]
isinstance(a, MyClass) Type Operatorsinstanceof is used to determine whether a PHP variable is an instantiated object of a certain class: Example #1 Using instanceof with classes
<?phpThe above example will output: bool(true) bool(false)
instanceof can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class: Example #2 Using instanceof with inherited classes
<?phpThe above example will output: bool(true) bool(true)
To check if an object is not an instanceof a class, the logical not operator can be used. Example #3 Using instanceof to check if object is not an instanceof a class
<?phpThe above example will output: bool(true)
Lastly, instanceof can also be used to determine whether a variable is an instantiated object of a class that implements an interface: Example #4 Using instanceof for class
<?phpThe above example will output: bool(true) bool(true)
Although instanceof is usually used with a literal classname, it can also be used with another object or a string variable: Example #5 Using instanceof with other variables
<?phpThe above example will output: bool(true) bool(true) bool(false)
There are a few pitfalls to be aware of. Before PHP version 5.1.0, instanceof would call __autoload() if the class name did not exist. In addition, if the class was not loaded, a fatal error would occur. This can be worked around by using a dynamic class reference, or a string variable containing the class name: Example #6 Avoiding classname lookups and fatal errors with instanceof in PHP 5.0
<?phpThe above example will output: bool(false)
The instanceof operator was introduced in PHP 5. Before this time is_a() was used but is_a() has since been deprecated in favor of instanceof. Note that as of PHP 5.3.0, is_a() is no longer deprecated. See also get_class() and is_a(). |
more
Recently updated
more
Most requested
|