Php check if object has property

PHP property_exists

Summary: in this tutorial, you’ll learn how to use the property_exists() function to check if the object or class has a property.

Introduction to the PHP property_exists function

The property_exists() function returns true if an object or a class has a property. Otherwise, it returns false .

Here’s the syntax of the property_exists() method:

property_exists(object|string $object_or_class, string $property): boolCode language: PHP (php)

The property_exists() method has two parameters:

  • The $object_or_class specifies the object or class that needs to check for the existence of a property.
  • The $property specifies the name of the property to check.

Note that in case of an error, the property_exists() function returns null instead.

PHP property_exists function examples

The following example uses the property_exists() function to check if the FileReader class has a specific property:

 class FileReader < private $filename; public $done; protected $filesize; public static $mimeTypes; > var_dump(property_exists(FileReader::class, 'filename')); // true var_dump(property_exists(FileReader::class, 'done')); // true var_dump(property_exists(FileReader::class, 'filesize')); // true var_dump(property_exists(FileReader::class, 'mimeTypes')); // true var_dump(property_exists(FileReader::class, 'status')); // falseCode language: PHP (php)

PHP property_exists function practical example

Suppose that you have a base class called Model . All the model classes need to extend this Model class.

To load a Model object from an associative array, you can define a load() method in the Model class as follows:

 abstract class Model < public function load(array $data): self < foreach ($data as $key => $value) < if (property_exists($this, $key)) < $this->$key = $value; > > return $this; > >Code language: PHP (php)

The load() method accepts an associative array as an argument. It iterates over the array element. If the object has a property that matches a key in the array, the load() method assigns the value to the property.

The following defines the User class that extends the Model class:

class User extends Model < private $username; private $email; private $password; >Code language: PHP (php)

To populate the properties of the User class with values of an array, you call the load() method like this:

$user = (new User())->load([ 'username' => 'john', 'email' => 'john@phptutorial.net', 'password' => password_hash('VerySecurePa$$1.', PASSWORD_DEFAULT), ]);Code language: PHP (php)

In practice, you would have a registration form. After the form is submitted, you need to validate the data in the $_POST array. And then you call the load() method to initialize a User object.

Summary

Источник

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
?>

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)

Источник

property_exists

Функция проверяет, существует ли атрибут property в указанном классе.

Замечание:

В противоположность isset() , property_exists() возвращает TRUE даже если свойство имеет значение NULL .

Список параметров

Имя класса или объекта класса для проверки

Возвращаемые значения

Возвращает TRUE , если свойство существует, FALSE — если оно не существует или NULL в случае ошибки.

Примечания

Замечание:

Вызов этой функции будет использовать все зарегистрированные функции автозагрузки, если класс еще не известен.

Замечание:

Функция property_exists() не определяет магически доступные свойства с помощью метода __get.

Список изменений

Версия Описание
5.3.0 Эта функция проверяет существование свойства вне зависимости от его доступности.

Примеры

Пример #1 Пример использования property_exists()

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, начиная с версии PHP 5.3.0
var_dump ( property_exists ( ‘myClass’ , ‘bar’ )); //false
var_dump ( property_exists ( ‘myClass’ , ‘test’ )); //true, начиная с версии PHP 5.3.0
myClass :: test ();

Смотрите также

Источник

Check if an object has a property in PHP

Posted on Sep 26, 2022

You can check whether a PHP object has a property or not by using the property_exists() function.

The property_exists() function can be used to check whether a property exists in a class or an object. The syntax is as follows:

You need to pass two things:
  1. The object or class as the first argument
  2. The property in string as the second argument

Here’s an example of calling the function:

      When checking the property of a class, you pass the class name as a string. When checking an object, you need to pass the object instance.

By passing the property name as a string as shown above, the property_exists() function will check whether the property exists in the given class name or object.

Now you’ve learned how to check if an object has a certain property in PHP. Great!

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Источник

Читайте также:  Text Outline
Оцените статью