php check object has property

property_exists

(PHP 5 >= 5.1.0, PHP 7, PHP 8)

property_exists — Checks if the object or class has a property

Description

This function checks if the given property exists in the specified class.

Parameters

The class name or an object of the class to test for

The name of the property

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

Notes

Using this function will use any registered autoloaders if the class is not already known.

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 ;

If you want to test if declared *public* property was unset, you can use the following code:

As of PHP 5.3.0, calling property_exists from a parent class sees private properties in sub-classes.

declared properties cannot be unset
any set property does exist, even being set to null, regardless how it was set

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

Источник

Tracking PHP Object property changes

I’m trying to track all changes made to a PHP variable. The variable can be an object or array.

For example it looks something like:

This object is then persisted to storage using an object-cache. When php script runs again.

So when the script runs the second time, or another script runs and modifies that object, I want those modifications to be tracked, either as they are being done, or in one go after the script executes.

I would like to know that ‘c’ was added to the object.

Now the actually code looks something like this:

I have tried a few methods, that work, but have downsides.

1) Wrap all objects in a class «Storable» which tracks changes to the object

The class «Storable» just saves the actual data object as a property, and then provides __get() and __set() methods to access it. When a member/property of the object is modified or added, the «Storable» class notes this. When a a property is accessed __get() on the Storable class returns the property, wrapped in another Storable class so that changes on that are tracked also, recursively for each new level.

The problem is that the objects are no longer native data types, and thus you cannot run array functions on arrays.

So instead we’d have to implement these array functions as methods of Storable.

This is all good, but I’d like to know if its possible to somehow use native functions, to reduce the overhead on the library I’m developing, while tracking changes so any changes can be added to persistent storage.

2) Forget about tracking changes, and just update whole object structures

This is the simplest method of keeping the objects in the program synchronized with the objects actually stored in the object-cache (which can be on a different machine).

However, it means whole structures, like an array with 1000 indexes, have to be sent though a socket to the object-cache when a single index changes.

3) Keep a mirror of the object locally

I’ve also tried cloning the object, and keeping a clone object untouched. Then when all processing is done by the PHP script, compare the clone to the modified object recursively, and submitting changed properties back to the object-cache.

This however requires that the whole object be downloaded in order to use it. It also requires that the object take up twice as much memory, since it is cloned.

I know this is pretty vague, but there is a quite a bit of code involved. If anyone wants to see the code I can post it, or put it up on an open SVN repo. The project is open source but I haven’t set up a public repository yet.

Источник

How to check that an object is empty in PHP?

How to find if an object is empty or not in PHP.

12 Answers 12

You can cast to an array and then check if it is empty or not

Edit: I didn’t realize they wanted to specifically check if a SimpleXMLElement object is empty. I left the old answer below

Updated Answer (SimpleXMLElement):

If by empty you mean has no properties:

If SimpleXMLElement is one level deep, and by empty you actually mean that it only has properties PHP considers falsey (or no properties):

If SimpleXMLElement is more than one level deep, you can start by converting it to a pure array:

Old Answer (simple object):

If you want to check if a simple object (type stdClass ) is completely empty (no keys/values), you can do the following:

Edit: added example

You can cast your object into an array, and test its count like so:

php check object has property. Смотреть фото php check object has property. Смотреть картинку php check object has property. Картинка про php check object has property. Фото php check object has property

Imagine if the object is not empty and in a way quite big, why would you waste the resources to cast it to array or serialize it.

This is a very easy solution I use in JavaScript. Unlike the mentioned solution that casts an object to array and check if it is empty, or to encode it into JSON, this simple function is very efficient concerning used resources to perform a simple task.

Using empty() won’t work as usual when using it on an object, because the __isset() overloading method will be called instead, if declared.

Therefore you can use count() (if the object is Countable).

Another possible solution which doesn’t need casting to array :

there’s no unique safe way to check if an object is empty

php’s count() first casts to array, but casting can produce an empty array, depends by how the object is implemented (extensions’ objects are often affected by those issues)

If you cast anything in PHP as a (bool), it will tell you right away if the item is an object, primitive type or null. Use the following code:

in PHP version 8

consider you want to access a property of an object, but you are not sure that the object itself is null or not and it could cause error. in this case you can use Nullsafe operator that introduced in php 8 as follow:

php check object has property. Смотреть фото php check object has property. Смотреть картинку php check object has property. Картинка про php check object has property. Фото php check object has property

If an object is «empty» or not is a matter of definition, and because it depends on the nature of the object the class represents, it is for the class to define.

PHP itself regards every instance of a class as not empty.

In short, you will have to come up with your own criteria for a specific object, and test them accordingly, either from outside the object or from a self-written isEmpty() method in the object.

Источник

Check if an object has changed

Is there a more native way (e.x. a built-in function) with less userland code to check if an objects property values have changed instead of using one of those methods:

The serialize approach

The shadow copy approach

Both approaches work. But both have disadvantages compared to a non userland implementation. The first one needs CPU for serialization and hashing and the second one needs memory for storing clones. And some classes may not be cloned.

Doesn’t PHP track changes at object properties? And does PHP not expose a method to make use of it?

php check object has property. Смотреть фото php check object has property. Смотреть картинку php check object has property. Картинка про php check object has property. Фото php check object has property

5 Answers 5

What you are trying to do?

You are trying to compare object with itself, after some chain of «unknown» operations to check if the object has changed. If this is true, there are some logical points to observe. At first, if you want to compare object with itself, you’ve got only two options:

There is no other logical approach. Comparing memory allocations, real objects, copying objects, comparing hashes, is all in point one. Tracking changes, saving changes inside object, remembering meantime operations, inside point 2.

So in my opinion this question is sort of backing up data questions. In that case there are many, many solutions but none of them are hardcoded inside php as far as I’m concerned. Why?

The answer is simple. PHP guys have got the same problems you’ve got :). Because if this would be hardocded inside php, then php should run / use one of those mechanisms (1) or (2).

In that case every object that you create, and every operation you made should be written somewhere to remember every state / object / something and use them for comparison in the future.

While you need this solution, almost

100% of websites don’t. So hardcoding this inside php would made

100% of websites work slower and your work faster ;).

PHP hypothetical solution?

There is also a problem, what to compare? You need to compare object with same object, but. Few minutes ago? Few operations ago? No. You must point exactly one place in code, and then point second place in code and compare object in those two places. So hypothetical auto tracking is. Kind of powerless, as there is no «key» in the object state ofer time array. I mean, even if you got magic_object_comparer function, what it should look like?

Sadly, you are left with own implementation.

After all, I would propose to implement some kind of own mechanism for that, and remember to use it only there, where you need it. As this mechanism will for sure be time and memory consuming. So think carefully:

And after all of that, try to implement it. I see that you’ve got a huge php knowledge, so I’m pretty sure that you will figure out something. There are also many comments, and possible ideas in this question and discussion.

But after all maybe I explained a little why, there is no build in solution, and why there should not be one in the future. :).

Источник

3 Ways to Check If an Object Has a Property in JavaScript

In this post, you’ll read 3 common ways to check for property existence in a JavaScript object.

Table of Contents

1. hasOwnProperty() method

In the following example, hasOwnProperty() determines the presence of properties name and realName :

On the other side, hero doesn’t have realName property. Thus hero.hasOwnProperty(‘realName’) returns false — denoting a missing property.

The method name hasOwnProperty() suggests that it looks in the own properties of the object. The own properties are those defined directly upon the object.

Because of that hasOwnProperty() doesn’t detect the inherited toString property:

Let’s use in operator to detect the existence of name and realName in hero object:

in operator has a short syntax, and I prefer it over hasOwnProperty() method.

The main difference between hasOwnProperty() method and in operator is that the latter checks within own and inherited properties of the object.

3. Comparing with undefined

Accessing a non-existing property from an object results in undefined :

hero.realName evaluates to undefined because realName property is missing.

Now you can see an idea: you can compare with undefined to determine the existence of the property.

Comparing with undefined to detect the existence of property is a cheap and dirty approach.

But be aware of false-negatives. If the property exists, but has undefined value (case, however, rarely happening), comparing against undefined evaluates incorrectly to false :

There are mainly 3 ways to check if the property exists.

hasOwnProperty() searches only within the own properties of the object.

The second approach makes use of propName in object operator. The operator evaluates to true for an existing property, and false otherwise.

in operator looks for properties existence in both own and inherited properties.

What’s your preferred way to check for properties existence?

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *