Php check if class has property

PHP Check if property exists

Question: I have a class with static properties and methods. Question: With classes containing private properties the property_exists() function returns true (php>5.3).

PHP Check if property exists

I have the following abstract class Types

abstract class DocumentTypes

This relates to the values that are stored in a table. The record MUST have a type and this is passed down. So for example, if someone is entering something that is for the OPERATIONAL part, then this would be the type that is entered into the database.

I have a function which handles this:

Now what I am trying to do is make sure that the property that is passed to handle is that of a property inside the abstract class Types the property OPERATIONAL exists, however, when I try to do the following:

$data = "asasfasfasfafs"; try < handle($data, DocumentTypes::OPERATIONAL); >catch(Exception $e)

I am getting the following exception thrown:

First parameter must either be an object or the name of an existing class in

How can I therefore check that the value passed, is in actual fact a property of the Types class?

Читайте также:  Чем удалить html теги

You just need to switch the parameter order around. The class name has to come first:

if(!property_exists(DocumentTypes::class $type)) . 

Check the documentation here.

Athough, the second parameter passed to property_exists must be a string, which is the name of the property you’re looking for. So it still won’t work if you’re looking for 1 .

UPDATE After reading some of your comments I think I understand what you’re trying to do now. You want to ensure that a user is passing a valid type though, and the valid types are being defined as separate constants.

This is the way I always solve this problem:

abstract class DocumentTypes < const OPERATIONAL = 1; const OTHER_TYPE = 2; public static function validTypes() < return [ DocumentTypes::OPERATIONAL, DocumentTypes::OTHER_TYPE, ]; >> 

Then you can use the validTypes function to verify the $type :

public function handle($type) < if (!in_array($type, DocumentTypes::validTypes(), true)) < throw new Exception("Property value must exist"); >> 

First, a property of a class is not the same as a constant of class. So the function property_exists() do not fits you.

To check, if the type (a cosnstat exists) you have to use the defined() function

Secondary — I did not understand what you actually need. Do you need to check — is there a constant defined, which value that matches the input value?

If yes — Then you can’t do it this way.

abstract class DocumentTypes < const OPERATIONAL = 1; >// -------------- function handle($type) < if (!defined('DocumentTypes::' . $type)) < throw new Exception('Property value must exist'); >> // -------------- $data = 'asasfasfasfafs'; try < handle($data); >catch(Exception $e)

Php stdClass check for property exist, 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_exists() to check if static property exists inside class method

I have a class with static properties and methods. One of my methods is a dynamic property grabber. I want to do this dynamically to prevent having a method for each property that I want to return. A single method would be nicer.

My problem is the method returns «Undefined Property». I have tried various solutions on the internet, but nothing seems to fit or work.

print_r(Generic::getProperty('propA')); 

This returns as if the property does not exist. In fact, the visibility doesn’t matter as they all return as if they don’t exist. Additionally, I know this works when not using static variables. I would rather continue to use static variables.

Updating my code from above to include namespaces. This was the problem that was causing the method to return undefined.

The updated code is as follows:

class Generic < public static $propA = "A"; private static $propB = "B"; protected static $propC = "C"; public static function getProperty(string $property): string < if (!property_exists('JLDN\Generic', $property)) : return "Undefined Property"; endif; return self::$$property; >> foreach (['propA', 'propB', 'propC', 'nonProperty'] as $prop) : printf("

Property: %s::%s - %s

\n", 'Generic', $prop, print_r(Generic::getProperty($prop), true)); endforeach;
Property: Generic::propA - A Property: Generic::propB - B Property: Generic::propC - C Property: Generic::nonProp - Undefined Property 

PHP JSON Check if value exists, PHP JSON Check if value exists [duplicate] Ask Question Asked 7 years, 7 months ago. Modified 7 years, 7 months ago. Viewed 4k times If it …

Correct PHP code to check if a variable exists

This code is part of a websocket server:

$msgArray = json_decode($msg); if ($msgArray->sciID)

It will either be receiving a json string like or a completely different json string with no sciID such as .

When the server receives the later, it echos out: Notice: Undefined property: stdClass::$sciID in /path/to/file.php on line 10

What is the correct code to check if $msgArray->sciID exists?

Use isset as a general purpose check (you could also use property_exists since you’re dealing with an object):

In case isset() or property_exists() doesn’t work, we can use array_key_exists()

if (array_key_exists("key", $array))

I’ve always done isset() but I’ve recently changed to !empty() and empty because one of my friends suggested it.

How to check if object of a class already exists in PHP?, The widgetfactory class is in widgetfactoryclass.php file, I have included this file in my index.php file, all my site actions runs through index.php, …

How do you validate if a property is accessible in php?

With classes containing private properties the property_exists() function returns true (php>5.3). With functions there is a method of is_callable that confirms not only the method exists but it is also available (as an alternative to method_exists()). Is there an equivalent counterpart to this function that will confirm if this property is accessible?

 public function visibleFunction() < return "visible"; >> $object = new testClass(); var_dump(property_exists($object, "unlocked")); // returns true var_dump(property_exists($object, "locked")); // returns true > php 5.3 var_dump(method_exists($object, "hiddenFunction")); // returns true but can't be called var_dump(method_exists($object, "visibleFunction")); // returns true var_dump(is_callable(array($object, "hiddenFunction"))); // returns false var_dump(is_callable(array($object, "visibleFunction"))); // returns true ?> 

You can use Reflection class taht will let you reverse-engineer classes, interfaces, functions, methods and extensions .

For example, to get all public properties of a class, you can do as follow :

$reflectionObject = new ReflectionObject($object); $testClassProperties = $reflectionObject->getProperties(ReflectionProperty::IS_PUBLIC); print_r ($testClassProperties); 
Array ( [0] => ReflectionProperty Object ( [name] => unlocked [class] => testClass ) ) 

to get all public methods of a class, you can do as follow :

$reflectionObject = new ReflectionObject($object); $testClassProperties = $reflectionObject->getMethods(ReflectionProperty::IS_PUBLIC); print_r ($testClassProperties); 
Array ( [0] => ReflectionMethod Object ( [name] => visibleFunction [class] => testClass ) ) 

Php — Check if property of object inside array exist, This is a lovely example of mutation and confusion with JSON and PHP, it’s possible that you start with an associative array in PHP, convert it to JSON and …

Источник

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

Источник

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() function in PHP

The property_exists() method checks if the object or class has a property.

Syntax

property_exists(object, property)

Parameters

  • object/ class − The object or the class name
  • property − The name of the property

Return

The property_exists() function returns TRUE if the property exists, FALSE if it doesn’t exist or NULL in case of an error.

Example

The following is an example −

 > var_dump(property_exists('Demo', 'one')); var_dump(property_exists(new Demo, 'one')); ?>

Output

The following is the output −

Samual Sam

Learning faster. Every day.

  • Related Articles
  • filter_has_var() function in PHP
  • filter_id() function in PHP
  • filter_input() function in PHP
  • filter_input_array() function in PHP
  • filter_list() function in PHP
  • filter_var_array() function in PHP
  • filter_var() function in PHP
  • constant() function in PHP
  • define() function in PHP
  • defined() function in PHP
  • die() function in PHP
  • eval() function in PHP
  • exit() function in PHP
  • get_browser() function in PHP
  • highlight_file() function in PHP

Источник

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