Php object has field

php property_exists() – Check if Property Exists in Class or Object

In php, we can check if a property exists in a class or an object with the built-in php property_exists() function.

class exampleClass < public $id; private $name; static protected $multiplyNumbers; static function multiplyNumbers($a,$b) < return $a * $b; >> var_dump(property_exists('exampleClass', 'name')); var_dump(property_exists(new exampleClass, 'name')); var_dump(property_exists('exampleClass', 'multiplyNumbers')); var_dump(property_exists('exampleClass', 'other')); // Output: bool(true) bool(true) bool(true) bool(false)

When working with objects in our php programs, it is useful to be able to check if an object has a certain property or not.

We can check if an object has a particular property in php with the php property_exists() function.

Below are some examples of using property_exists() in php to check if a property exists in a php object.

class exampleClass < public $id; private $name; static protected $multiplyNumbers; static function multiplyNumbers($a,$b) < return $a * $b; >> var_dump(property_exists('exampleClass', 'name')); var_dump(property_exists(new exampleClass, 'name')); var_dump(property_exists('exampleClass', 'multiplyNumbers')); var_dump(property_exists('exampleClass', 'other')); // Output: bool(true) bool(true) bool(true) bool(false)

Checking if a Property Exists in php Object with Exception Handling

Another way you can check if a property exists in a php object is with exception handling.

When you try to access a property and the property doesn’t exist, then you will get an error. If you don’t get an error, you know the property is there.

Читайте также:  Структуры типов данных javascript

Therefore, using this logic, we can check if a property exists in an object.

Below is an example in php of checking if different properties exist using exception handling.

class exampleClass < public $id; private $name; static protected $multiplyNumbers; static function multiplyNumbers($a,$b) < return $a * $b; >> try < exampleClass::doSomething(); >catch(Error | Exception $e) < echo "\n Exception Caught: ", $e->getMessage(); > try < exampleClass::multiplyNumbers(2,3); echo "\n This works!"; >catch(Error | Exception $e) < echo "\n Exception Caught: ", $e->getMessage(); > //Output: Exception Caught: Call to undefined method exampleClass::doSomething() This works!

Hopefully this article has been useful for you to learn how to check if an object has an property or not in php.

  • 1. Capitalize First Letter of String with php ucfirst() Function
  • 2. php array_filter() – Filter Array Elements with Function in php
  • 3. php pi – Get Value of pi Using php pi() Function
  • 4. php array_slice() – Get Slice of Elements from Array
  • 5. Using function_exists() to Check if Function Exists in php
  • 6. Reversing an Array in php with array_reverse() Function
  • 7. How to Reverse Array in php Without a Function or Other Variables
  • 8. How to Add Items to Array in php
  • 9. php acos – Find Arccosine and Inverse Cosine of Number
  • 10. php asinh – Find Hyperbolic Arcsine of Number Using php asinh() Function

About The Programming Expert

The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.

Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.

At the end of the day, we want to be able to just push a button and let the code do it’s magic.

You can read more about us on our about page.

Источник

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)

Источник

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

Источник

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 ();

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

Источник

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