Php class var exist

property_exists

This function checks if the given property exists in the specified class.

Note:

As opposed with isset() , property_exists() returns true even if the property has the value null .

Parameters

The class name or an object of the class to test for

Return Values

Returns true if the property exists, false if it doesn’t exist or null in case of an error.

Examples

Example #1 A property_exists() example

class myClass public $mine ;
private $xpto ;
static protected $test ;

static function test () var_dump ( property_exists ( ‘myClass’ , ‘xpto’ )); //true
>
>

var_dump ( property_exists ( ‘myClass’ , ‘mine’ )); //true
var_dump ( property_exists (new myClass , ‘mine’ )); //true
var_dump ( property_exists ( ‘myClass’ , ‘xpto’ )); //true
var_dump ( property_exists ( ‘myClass’ , ‘bar’ )); //false
var_dump ( property_exists ( ‘myClass’ , ‘test’ )); //true
myClass :: test ();

Notes

Note:

Using this function will use any registered autoloaders if the class is not already known.

Note:

The property_exists() function cannot detect properties that are magically accessible using the __get magic method.

See Also

User Contributed Notes 10 notes

The function behaves differently depending on whether the property has been present in the class declaration, or has been added dynamically, if the variable has been unset()

$testObject = new TestClass ;

var_dump ( property_exists ( «TestClass» , «dynamic» )); // boolean false, as expected
var_dump ( property_exists ( $testObject , «dynamic» )); // boolean false, same as above

$testObject -> dynamic = null ;
var_dump ( property_exists ( $testObject , «dynamic» )); // boolean true

unset( $testObject -> dynamic );
var_dump ( property_exists ( $testObject , «dynamic» )); // boolean false, again.

var_dump ( property_exists ( $testObject , «declared» )); // boolean true, as espected

unset( $testObject -> declared );
var_dump ( property_exists ( $testObject , «declared» )); // boolean true, even if has been unset()

If you are in a namespaced file, and you want to pass the class name as a string, you will have to include the full namespace for the class name — even from inside the same namespace:

property_exists(«A», «foo»); // false
property_exists(«\\MyNS\\A», «foo»); // true
?>

protected $_name ;
protected $_email ;

public function __call ( $name , $arguments ) $action = substr ( $name , 0 , 3 );
switch ( $action ) case ‘get’ :
$property = ‘_’ . strtolower ( substr ( $name , 3 ));
if( property_exists ( $this , $property )) return $this ->< $property >;
>else echo «Undefined Property» ;
>
break;
case ‘set’ :
$property = ‘_’ . strtolower ( substr ( $name , 3 ));
if( property_exists ( $this , $property )) $this -> < $property >= $arguments [ 0 ];
>else echo «Undefined Property» ;
>

$s = new Student ();
$s -> setName ( ‘Nanhe Kumar’ );
$s -> setEmail ( ‘nanhe.kumar@gmail.com’ );
echo $s -> getName (); //Nanhe Kumar
echo $s -> getEmail (); // nanhe.kumar@gmail.com
$s -> setAge ( 10 ); //Undefined Property
?>

Читайте также:  Page Title

If you want to test if declared *public* property was unset, you can use the following code:

$a = new A ();
$is_defined = array_key_exists ( ‘declared’ , (array) $a ); //=>true

unset( $a -> declared );
$is_defined = array_key_exists ( ‘declared’ , (array) $a ); //=>false
?>

As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

class Child extends P private $prop1 ;
>

$child = new Child ();
var_dump ( $child -> test_prop ( ‘prop1’ )); //true, as of PHP 5.3.0

abstract class P private $priv ;
static protected $static_prop ;
static function exists ( $prop = ‘priv’ ) var_dump ( property_exists (new static, $prop )); //true
>
>

class S extends P static protected $new_prop ;
>
S :: exists ( ‘new_prop’ ); // True
S :: exists ( ‘static_prop’ ); // True
S :: exists ( ‘priv’ ); // True

$a = array(‘a’,’b’=>’c’);
print_r((object) $a);
var_dump( property_exists((object) $a,’0′));
var_dump( property_exists((object) $a,’b’));

For class constants, use defined() to check for their existence since property_exists() cannot be used.
class A private static $c = ‘C’ ;
const B = ‘B’ ;
>
if( property_exists ( ‘A’ , ‘c’ )=== true ) echo ‘y’ ;
>else echo ‘n’ ;
> //output: y
if( property_exists ( ‘A’ , ‘B’ )=== true ) echo ‘y’ ;
>else echo ‘n’ ;
> //output: n
if( defined ( ‘A::B’ )=== true ) echo ‘y’ ;
>else echo ‘n’ ;
> //output: y
?>

declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

public $my_public ;
protected $my_protected ;
private $my_private ;

function __construct () $this -> dumper ( ‘before-constructed’ );
$this -> my_constructed_int = 123 ;
$this -> my_constructed_null = null ;
$this -> dumper ( ‘after-constructed’ );
>

public function dumper ( $name ) printf ( «\n[%s] dump:\n» , $name );

foreach ( $this -> my_checklist () as $prop ) printf ( «[%s]:\t» , $prop );
var_dump ( property_exists ( $this , $prop ));
>
>

public function unset_all () foreach ( $this -> my_checklist () as $prop ) unset( $this -> $prop );
>
>

private function my_checklist () return array( ‘my_public’ , ‘my_protected’ , ‘my_private’ , ‘my_constructed_int’ , ‘my_constructed_null’ , ‘my_assigned_int’ , ‘my_assigned_null’ ,);
>

$object = new demo_property_exists ();
$object -> dumper ( ‘before-assigned’ );
$object -> my_assigned_int = 456 ;
$object -> my_assigned_null = null ;
$object -> dumper ( ‘after-assigned’ );
$object -> unset_all ();
$object -> dumper ( ‘after-unset’ );

[before-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false) [after-constructed] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false) [before-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false) [after-assigned] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(true)
[my_constructed_null]: bool(true)
[my_assigned_int]: bool(true)
[my_assigned_null]: bool(true) [after-unset] dump:
[my_public]: bool(true)
[my_protected]: bool(true)
[my_private]: bool(true)
[my_constructed_int]: bool(false)
[my_constructed_null]: bool(false)
[my_assigned_int]: bool(false)
[my_assigned_null]: bool(false)

Источник

class_exists

This function checks whether or not the given class has been defined.

Читайте также:  Javascript создание пользовательских функций

Parameters

The class name. The name is matched in a case-insensitive manner.

Whether to autoload if not already loaded.

Return Values

Returns true if class is a defined class, false otherwise.

Examples

Example #1 class_exists() example

// Check that the class exists before trying to use it
if ( class_exists ( ‘MyClass’ )) $myclass = new MyClass ();
>

Example #2 autoload parameter example

spl_autoload_register (function ( $class_name ) include $class_name . ‘.php’ ;

// Check to see whether the include declared the class
if (! class_exists ( $class_name , false )) throw new LogicException ( «Unable to load class: $class_name » );
>
>);

if ( class_exists ( MyClass ::class)) $myclass = new MyClass ();
>

See Also

  • function_exists() — Return true if the given function has been defined
  • enum_exists() — Checks if the enum has been defined
  • interface_exists() — Checks if the interface has been defined
  • get_declared_classes() — Returns an array with the name of the defined classes

User Contributed Notes 9 notes

If you are using aliasing to import namespaced classes, take care that class_exists will not work using the short, aliased class name — apparently whenever a class name is used as string, only the full-namespace version can be used

use a\namespaced\classname as coolclass;

class_exists( ‘coolclass’ ) => false

Note: class_exists() check only classes!
interface DemoInterface <>;
var_dump ( class_exists ( ‘DemoInterface’ )); // false
trait DemoTrait <>;
var_dump ( class_exists ( ‘DemoTrait’ )); // false
class DemoClass <>;
var_dump ( class_exists ( ‘DemoClass’ )); // true
?>

Common function:
/**
* Checks if the class/trait/interface has been defined.
*
* @param string $name The case-insensitive name of class/trait/interface
* @param bool $autoload Whether to call spl_autoload()
* @return bool
*/
function structure_exists ( string $name , bool $autoload = true ): bool
return class_exists ( $name , $autoload )
|| interface_exists ( $name , $autoload )
|| trait_exists ( $name , $autoload );
>
?>

Beware: class_exists is case-INsensitive, as is class instantiation.

php > var_dump(class_exists(«DomNode»));
bool(true)
php > var_dump(class_exists(«DOMNode»));
bool(true)
php > var_dump(class_exists(«DOMNodE»));
bool(true)
php > $x = new DOMNOdE();
php > var_dump(get_class($x));
string(7) «DOMNode»

(tested with PHP 5.5.10 on Linux)

This can cause some headaches in correlating class names to file names, especially on a case-sensitive file system.

If you recursively load several classes inside an autoload function (or mix manual loading and autoloading), be aware that class_exists() (as well as get_declared_classes()) does not know about classes previously loaded during the *current* autoload invocation.

Apparently, the internal list of declared classes is only updated after the autoload function is completed.

Hi guys!
Be careful and don’t forget about second boolean argument $autoload (TRUE by default) when check exists class after spl_autoload_register. Propose short example
file second.php
class Second <>
?>
file index.php
class First
function first ( $class , $bool ) spl_autoload_register ( function( $class ) require strtolower ( $class ) . ‘.php’ ;
>);
echo class_exists ( $class , $bool )? ‘Exist. ‘ : ‘Not exist!’ ;
>
>

Читайте также:  Log request body java

new First ( $class = ‘Second’ , $bool = true ); //Exist.
new First ( $class = ‘Second’ , $bool = false ); //Not exist!
?>
Because __autoload executing much earlier than boolean returned, imho..

If you are checking if a class exists that is in a specific namespace then you have to pass in the full path to the class:

echo (class_exists(«com::richardsumilang::common::MyClass»)) ? «Yes» : «No»;

If you have a directory of classes you want to create. (Modules in my instance). you can do it like that

I’m running PHP 5.3.4 on Windows 7 and had some difficulty autoloading classes using class_exists(). In my case, when I checked for the class and it didn’t exist, class_exists automatically threw a system Exception. I was also throwing my own exception resulting in an uncaught exception.

/**
* Set my include path here
*/
$include_path = array( ‘/include/this/dir’ , ‘/include/this/one/too’ );
set_include_path ( $include_path );
spl_autoload_register ();
/**
* Assuming I have my own custom exception handler (MyException) let’s
* try to see if a file exists.
*/
try if( ! file_exists ( ‘myfile.php’ ) ) throw new MyException ( ‘Doh!’ );
>
include( ‘myfile.php’ );
>
catch( MyException $e ) echo $e -> getMessage ();
>
/**
* The above code either includes myfile.php or throws the new MyException
* as expected. No problem right? The same should be true of class_exists(),
* right? So then.
*/
$classname = ‘NonExistentClass’ ;
try if( ! class_exists ( $classname ) ) throw new MyException ( ‘Double Doh!’ );
>
$var = new $classname ();
>
catch( MyException $e ) echo $e -> getMessage ();
>
/**
* Should throw a new instance of MyException. But instead I get an
* uncaught LogicException blah blah blah for the default Exception
* class AND MyException. I only catch MyException so we’ve got on
* uncaught resulting in the dreaded LogicException error.
*/
?>

By registering an additional autoload handler function that did nothing, I was able to stop throwing the extra Exception and only throw my own.

/**
* Set my include path here
*/
$include_path = array( ‘/include/this/dir’ , ‘/include/this/one/too’ );
set_include_path ( $include_path );
spl_autoload_register ();
spl_autoload_register ( ‘myAutoLoad’ ); // Add these two and no worries.
function myAutoLoad () <>
/**
* By registering the additional custom autoload function that does nothing
* class_exists() returns only boolean and does NOT throw an uncaught Exception
*/
?>

Found this buried in some search results. I don’t remember the page URL but if it would have been here it might have saved me some time!

If spl_autoload_register() had been called, then function will try autoload class if it does not exists.

Use instead
in_array ( $class_name , get_declared_classes ());
?>

  • Classes/Object Functions
    • class_​alias
    • class_​exists
    • enum_​exists
    • get_​called_​class
    • get_​class_​methods
    • get_​class_​vars
    • get_​class
    • get_​declared_​classes
    • get_​declared_​interfaces
    • get_​declared_​traits
    • get_​mangled_​object_​vars
    • get_​object_​vars
    • get_​parent_​class
    • interface_​exists
    • is_​a
    • is_​subclass_​of
    • method_​exists
    • property_​exists
    • trait_​exists
    • _​_​autoload

    Источник

Оцените статью