PHP Check Whether Property Exists in Object or Class

PHP check whether property exists in object or class

property_exists( mixed $class , string $property )

if (property_exists($ob, 'a')) 

isset( mixed $var [, mixed $... ] )

NOTE : Mind that isset() will return false if property is null

if (isset($ob->a))

Example 1:

$ob->a = null
var_dump(isset($ob->a)); // false

Example 2:

class Foo
{
public $bar = null;
}

$foo = new Foo();

var_dump(property_exists($foo, 'bar')); // true
var_dump(isset($foo->bar)); // false

Php check if object with property exists in array

PHP also has an array filtering functioning, which (for obvious reasons) is called array_filter() and does what you want, with anonymous functions.

function findAllWithId($objects, $id) {
return array_filter($objects, function($toCheck) use ($id) {
return $toCheck->id == $id;
});
}

Check if a property exists on magically set properties

I don't believe there's a way to alter the functionality of property_exists() using magic methods; here's a list of available magic methods in PHP. However, you should be able to alter isset() to use any logic you like.

class test {

private $data = array();

public function __get($key) {
echo "get $key\n";
return array_key_exists($key, $this->data) ? $this->data[$key] : null;
}

public function __set($key, $value) {
echo "set $key = $value\n";
$this->data[$key] = $value;
}

public function __isset($key) {
echo sprintf("isset $key ( returns %b )", array_key_exists($key, $this->data));
return array_key_exists($key, $this->data);
}

}

$test = new test();
$test->x = 42;
isset($test->x); // 1

$test->y = null;
isset($test->y); // 1

This effectively fixes the (annoying) problem with isset and nulls by overriding its functionality through the magic method. Instead of using isset() within __isset() however, we use array_key_exists (which handles nulls as you would expect). Thus __isset() returns the expected result when a null value is set.

This has a downside, namely that the overridden functionality does not produce the same results as default isset() functionality. So, if this object needs to be used transparently with other (perhaps stdClass) objects, then isset() will return true for null values in objects of this class, and false for null values in normal objects.

Depending on your needs then this may or may not be a viable solution. If the above issue is a hindrance, then another option might be to define an interface with a keyIsSet() property, and apply that interface to all objects to be tested. Then use $obj->keyIsSet('key') rather than isset($obj->$key). Not as elegant, but a bit better oo.

Check if object has given properties

You can use at least three ways to do it:

  • property_exists()
  • isset()
  • ReflectionClass::hasProperty()

All of these are demonstrated below:

<?php
class myClass
{
public $a=1;
public $b=2;
public $c=3;
}

$myObj = new myClass();
$reflectionClass = new ReflectionClass($myObj);
foreach (['a', 'b', 'c', 'd'] as $property)
{
printf("Checking if %s exists: %d %d %d\n",
$property,
property_exists($myObj, $property),
isset($myObj->$property),
$reflectionClass->hasProperty($property));
}

Output:

Checking if a exists: 1 1 1
Checking if b exists: 1 1 1
Checking if c exists: 1 1 1
Checking if d exists: 0 0 0

Each column is a result of applying corresponding technique from the top of my post.

property_exists() to check if static property exists inside class method

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("<p>Property: %s::%s - %s</p>\n", 'Generic', $prop, print_r(Generic::getProperty($prop), true));
endforeach;

Output:

Property: Generic::propA - A

Property: Generic::propB - B

Property: Generic::propC - C

Property: Generic::nonProp - Undefined Property

php stdClass check for property exist

Change

if(property_exists($sale, gpps)) 

with

if(property_exists($sale, "gpps"))

notice how now gpps is passed as string, as per the signature of the property_exists function:

bool property_exists ( mixed $class , string $property )

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.

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

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

OUTPUT

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

OUTPUT

Array
(
[0] => ReflectionMethod Object
(
[name] => visibleFunction
[class] => testClass
)

)

PHP std::Class check if attribute exists

Use a loop + property_exists function:

foreach($myArray as $obj)
{
if(!property_exists($obj, 'media') || !is_array($obj->media))
{
echo("property 'media' does not exist in $obj");
// throw exception, fill in default value for media array, set variable, whatever.
}
}

PHP Check if property exists -- always returning false

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");
}
}


Related Topics



Leave a reply



Submit