I'm having trouble understanding the behavior of a WP_Post
variable (and / or possibly the behavior of var_dump
itself).
As far as I know, var_dump
will inspect all data from a variable. From the PHP documentation:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
Then, why is it that var_dump($post)
doesn't show metadata, whereas var_dump($post->metadata)
does?
I've already read the offficial documentation, specially this particular comment, as well as this answer. I assume the explanation is there, in plain sight -- however, it's still unclear to me.
What's going on here? Is it some basic PHP behavior that I'm not aware? (I'm not sure if this question is because a lack of understanding how WordPress works or how PHP works. Sorry if this is the wrong site to ask).
I'm having trouble understanding the behavior of a WP_Post
variable (and / or possibly the behavior of var_dump
itself).
As far as I know, var_dump
will inspect all data from a variable. From the PHP documentation:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
Then, why is it that var_dump($post)
doesn't show metadata, whereas var_dump($post->metadata)
does?
I've already read the offficial documentation, specially this particular comment, as well as this answer. I assume the explanation is there, in plain sight -- however, it's still unclear to me.
What's going on here? Is it some basic PHP behavior that I'm not aware? (I'm not sure if this question is because a lack of understanding how WordPress works or how PHP works. Sorry if this is the wrong site to ask).
There is no 'magic' in it, but there are two magic
methods of WP_Post
class, __isset()
, and __get()
.
Your extra_data
is not a property of WP_Post
class, so first var_dump
does not include it.
A reference to non existing property of WP_Post
employs those magic
methods, mentioned above, to retrieve post's metadata.
First, $post->__isset('extra_data')
will be executed, if false
is returned, then $post->extra_data
will be an empty array, otherwise $post->__get('extra_data')
will run, returning metadata. That's why your second var_dump
shows extra_data
.
Note: Milo's first comment to this question is, in fact, the perfect answer.