|
|
 |
PHP tiene un operador único de tipo:
instanceof es usado para determinar si un
objeto dado, sus padres o sus implementaciones de interfaces son de una
clase de objeto
especificada.
El operador instanceof fue introducido en PHP
5. Antes de esta versión, is_a() era
utilizado, pero is_a() ha sido marcado como
obsoleto desde entonces en favor de instanceof.
Vea también get_class() e
is_a().
add a note
User Contributed Notes
Operadores de Tipo
MikeH
10-Mar-2006 03:14
This will fail:
<?
if ($moo instanceof "Moo") echo "Goo\n";
?>
and this will not:
<?
if ($moo instanceof Moo) echo "Goo\n";
?>
and although you cant use a quoted string as the class name to check, you can use a variable like this:
<?
$moo_class = "Moo";
if ($moo instanceof $moo_class) echo "Goo\n";
?>
so if you want to loop through an array of class names to check an object against, you can do it easily.
arnold at bean-it dot nl
24-Feb-2006 03:28
Note that operator 'instanceof' will trigger the autoloader.
If the class does not exists, it is not possible that the object is an instance of this class (as shown by glen at arkadia-systems dot com). Loading this class will probably be a waste of excecution time, so use class_exists with $autoload set to false before using instanceof.
<?php
function __autoload($classname)
{
if (($fp = @fopen("$classname.php", 'r', 1)) and fclose($fp)) include_once "$classname.php";
}
function foo($obj)
{
if (class_exists('ABC', false) && $obj instanceof ABC) echo "object is an ABC";
}
?>
Colin
05-Dec-2005 11:20
To MooGoo:
This will fail, as you pointed out:
<?
if ($moo instanceof "Moo") echo "Goo\n";
?>
but this will not
<?
if ($moo instanceof Moo) echo "Goo\n";
?>
This later example (no quotes around Moo) is shown twice in the example code.
klaazvaag . gmail . com
03-Oct-2005 02:02
If you wish to do a short but dynamic comparison using instanceof, you can use this code:
<?php
class any
{
function __construct($obj)
{
if (is_object($obj))
if ($obj instanceof self)
echo '$obj is an instance of '.__CLASS__;
}
}
?>
MooGoo
01-Sep-2005 07:42
instanceof can compare a class instance to a string which contains a class name. However that string must be contained in a variable, it will not work as a return value from a function (for instance, get_class()) or even from a regular inline string.
<?php
class Moo
{
function Goo()
{
$moo = "I do nothing";
}
}
$moo = new Moo;
if ($moo instanceof "Moo") echo "Goo\n";
if ($moo instanceof get_class($moo)) echo "Goo\n";
$className = get_class($moo);
if ($moo instanceof $className) echo "Goo\n";
$className = "Moo";
if ($moo instanceof $className) echo "Goo\n";
?>
archanglmr at yahoo dot com
17-Feb-2005 06:37
Negated instanceof doesn't seem to be documented. When I read instanceof I think of it as a compairson operator (which I suppose it's not).
<?php
class A {}
class X {}
if (new X !instanceof A) {
throw new Exception('X is not an A');
}
if (!(new X instanceof A)) {
throw new Exception('X is not an A');
}
?>
d dot schneider at 24you dot de
18-Dec-2004 12:42
use this for cross-version development...
<?php
function is_instance_of($IIO_INSTANCE, $IIO_CLASS){
if(floor(phpversion()) > 4){
if($IIO_INSTANCE instanceof $IIO_CLASS){
return true;
}
else{
return false;
}
}
elseif(floor(phpversion()) > 3){
return is_a($IIO_INSTANCE, $IIO_CLASS);
}
else{
return false;
}
}
?>
glen at arkadia-systems dot com
10-Sep-2004 10:00
If you are updating code to replace 'is_a()' with the PHP5 compliant
'instanceof' operator, you may find it necessary to change the basic
architecture of your code to make this work.
'instanceof' will throw a fatal error if the object being checked for does not
exist.
'is_a()' will simply return false under this condition.
In the example below, 'is_a()' would effectively detect the need to create an
instance of class 'A', but in this case 'instanceof' will crash your program
with a fatal error.
<?php
class B {}
$thing = new B();
if (is_a($thing, 'A')) {
echo 'Yes, $thing is_a A<br>';
} else {
echo 'No, $thing is not is_a A<br>';
}
if ($thing instanceof A) {
echo 'Yes, $thing is an instaceof A<br>';
} else {
echo 'No, $thing is not an instaceof A<br>';
}
?>
>>> Output:
No, $thing is not is_a A
Fatal error: Class 'A' not found in is_a-instanceof.php on line 19
>>>
A suitable work-around for this situation is to check for the existence of the
class before performing the 'instanceof' comparison:
<?php
if (class_exists('A') && $thing instanceof A) {
echo 'Yes, $thing is an instaceof A<br>';
} else {
echo 'No, $thing is not an instaceof A<br>';
}
?>
zimba dot spam at gmail dot com
10-Sep-2004 12:17
instanceof cannot use a string for the comparison like is_a.
Instead, you can use a class instance (not documented)
Example :
<?
$x = new myClass();
$y = new myClass();
echo is_a($x, get_class($y)); echo $x instanceof get_class($y); echo $x instanceof $y;
?>
Cheers,
zimba
"Leo Pedretti" <lpedretti at suserver dot com>
24-Aug-2004 08:59
The instanceof operator also checks the interface tree. For example, the following code:
<?
interface Human {
public function say($var);
public function gender();
}
class man implements Human {
public function say($var) {
"Oh yeah, $var\n"
}
public function gender() {
return "male";
}
}
class woman implements Human {
public function say($var) {
"Oh dear, $var\n"
}
public function gender() {
return "female";
}
}
$m = new man;
$w = new woman;
if ($p instanceof Human) {
print "\$p is Human.\n";
} else {
print "\$p is not Human.\n";
}
print "\$m is of gender ".$m->gender()."\n";
if ($w instanceof Human) {
print "\$w is Human.\n";
} else {
print "\$w is not Human.\n";
}
print "\$w is of gender ".$w->gender()."\n";
?>
Will produce the output
$m is Human.
$m is of gender male
$w is Human.
$w is of gender female
Jesse Scott (scotje at wwc dot edu)
06-Jul-2004 06:52
Since it's not stated authoritatively here, I'll add that instanceof *does* check all the way up the inheritence tree.
So in this code:
<?php
class A
{
var $someProp;
}
class B extends A
{
function showProp()
{
echo $someProp;
}
}
$obj1 = new B;
if ($obj1 instanceof A)
echo "Instanceof checks inheritence tree!";
else
echo "Instanceof does not check inheritence tree!";
?>
The first branch of the if/else block is executed since ($obj1 instanceof A) evaulates to TRUE.
| |
|
| Chiste de... Parecidos razonables | | Casas | - ¿En qué se parece una casa que se quema a otra deshabitada?
- En que de una salen llamas y en otras llamas y no salen. | | Chistes en tu mail | | ©ContenidosGratis |
| Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos |  | Cake Mania Jugadores: 6835 Categoría del juego: Acción Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero. |
|  | Rainbow Web Jugadores: 2199 Categoría del juego: Puzzles Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente. |
|  | Mahjongg Fortuna Jugadores: 12462 Categoría del juego: Solitarios Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta. |
|  | Chainz 2 Jugadores: 6955 Categoría del juego: Puzzles Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más. |
|  | Delicious Jugadores: 4405 Categoría del juego: Acción Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues! |
|  | Bookworm Jugadores: 4568 Categoría del juego: Palabras Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos! |
|  | Zuma Jugadores: 4976 Categoría del juego: Acción Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás! |
|  | Jewel of Atlantis Jugadores: 3798 Categoría del juego: Puzzles Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis. |
|  | Jewel Quest Jugadores: 3727 Categoría del juego: Puzzles Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos! |
|  | Bejeweled 2 Jugadores: 3659 Categoría del juego: Puzzles Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca. |
|
|