Check If a Property Exists in a Class

Check if a property exists in a class

Your method looks like this:

public static bool HasProperty(this object obj, string propertyName)
{
return obj.GetType().GetProperty(propertyName) != null;
}

This adds an extension onto object - the base class of everything. When you call this extension you're passing it a Type:

var res = typeof(MyClass).HasProperty("Label");

Your method expects an instance of a class, not a Type. Otherwise you're essentially doing

typeof(MyClass) - this gives an instanceof `System.Type`. 

Then

type.GetType() - this gives `System.Type`
Getproperty('xxx') - whatever you provide as xxx is unlikely to be on `System.Type`

As @PeterRitchie correctly points out, at this point your code is looking for property Label on System.Type. That property does not exist.

The solution is either

a) Provide an instance of MyClass to the extension:

var myInstance = new MyClass()
myInstance.HasProperty("Label")

b) Put the extension on System.Type

public static bool HasProperty(this Type obj, string propertyName)
{
return obj.GetProperty(propertyName) != null;
}

and

typeof(MyClass).HasProperty("Label");

How to check if property exists

You can try like this:

OBJECT.GetType().GetProperty("PROPERTY") != null

So in your code it would be like:

var a = one DirectoryEntry record;
var pi = a.GetType().GetProperty("employeeNumber");
var value = pi.GetValue(a, null);

EDIT:-

Try this:

bool x = a.Properties.Contains("employeeNumber");

How do I check if an object has an attribute?

Try hasattr():

if hasattr(a, 'property'):
a.property

See zweiterlinde's answer below, who offers good advice about asking forgiveness! A very pythonic approach!

The general practice in python is that, if the property is likely to be there most of the time, simply call it and either let the exception propagate, or trap it with a try/except block. This will likely be faster than hasattr. If the property is likely to not be there most of the time, or you're not sure, using hasattr will probably be faster than repeatedly falling into an exception block.

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

Check if a property exists in a list of custom class

If you have a class named Foo and you want to check if a property Bar exists you can do the following using reflection:

bool barExists = typeof(Foo).GetProperties()
.Where(x => x.Name == "Bar")
.Any();

or shorter even (thanks for the reminder @Adam Robinson):

bool barExists = typeof(Foo).GetProperties().Any(x => x.Name == "Bar")

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

How to check if object property exists with a variable holding the property name?

var myProp = 'prop';
if(myObj.hasOwnProperty(myProp)){
alert("yes, i have that property");
}

Or

var myProp = 'prop';
if(myProp in myObj){
alert("yes, i have that property");
}

Or

if('prop' in myObj){
alert("yes, i have that property");
}

Note that hasOwnProperty doesn't check for inherited properties, whereas in does. For example 'constructor' in myObj is true, but myObj.hasOwnProperty('constructor') is not.

Check if class property value exists in list of objects

Use any:

class ButtonPress():
def __init__(self, time, button):
self.time = time
self.button = button

buttonlist = []
buttonlist.append(ButtonPress("25", "a"))
buttonlist.append(ButtonPress("5", "b"))

if any(button.time == "25" for button in buttonlist):
print("yaaay")
else:
print("feck")

Output

yaaay

An alternative using in is the following:

if "25" in (button.time for button in buttonlist):

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.



Related Topics



Leave a reply



Submit