2

suppose I have two classes

class A extends class B

class A has its own fields class B has its own fields

since class A extends B, class A also contains the fields of B

Is there a way to get a list of fields that are only for class A and not fields that are inherited from B since calling get_object_vars() on an object of class A would also return fields from class B

1 Answer 1

3

You can do:

array_diff(get_object_vars($objectA), get_object_vars($objectB));

Edit, you can also do the same with classes:

array_diff(get_class_vars(CLASS A), get_class_vars(CLASS B));
Sign up to request clarification or add additional context in comments.

3 Comments

It is about objects, not classes. Do you want to see examples of code that your solution will fail? What about when you unset some properties during creation of the object of child class? What about properties assigned within some of the methods?
By 'fail' I meant 'provide incorrect results', not fail in the sense of throwing exceptions (something you described as being biased). Your code would result in warnings only when $objectA or $objectB is not an object, but this is in no means a problem with this code.
First he himself speak about using get_objects_vars() on an object. Secondly let's assume that class b has one property call foo, and class a has another property call boo. My code will return boo. Now if you decide to unset boo on you object a, and use my code, my code will return an empty array. Which mis not true for the class a but is totally correct for the object a. Moreover you can use get_class_vars() to do exactly the same on a class.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.