I have the following variable available inside a view:
$recent_posts
It is an array so I performed a foreach loop on it and var dumped the result like so:
<? foreach($recent_posts as $post): ?>
<pre><?= var_dump($post) ?></pre>
<? endforeach ?>
This is the output I received from the vardump:
Array
(
[obj] => models\Tag Object
(
[large_image:protected] =>
[small_image:protected] =>
[_obj_id] => 13493
[_validator] =>
[_values:protected] => Array
(
)
[_dirty_values:protected] => Array
(
)
[_type:protected] =>
[_properties:protected] => Array
(
)
[_is_loaded:protected] =>
[_is_static:protected] =>
)
)
How can I retrieve the values for each post. For example how can I get the large_image
for a post? I tried this (without knowing what the heck I'm doing) and not surprisingly it didn't work:
<?= $post->large_image ?>
large_image
is protected
, you cannot access protected
members
out side of the class ( this
context).
You have two options, add a getter
function for large_image
or make it public
.
getter
is a function that exposes private
or protected
member, for example
public function get_large_image(){
return $this->large_image;
}
Since $post->large_image
is a protected property, you are not allowed to access it outside of the class (or derived classes). I presume there might be a getter method by which you will be able to retrieve the value though (something like get_large_image()
perhaps).
To determine what methods are available on the object, either view the source code of the accompanying class, or use reflection:
$refl = new ReflectionClass( $post );
var_dump( $refl->getMethods() );
If there's no method available to get the value, I would not advise you to alter the class, by making the property public (it's been made protected for a reason I presume), or alter the class at all, if it is not your own.
Rather, I would suggest, if possible, you extend the class and create a getter method for the value:
<?php
class MyTag
extends Tag
{
// I would personally prefer camelCase: getLargeImage
// but this might be more in line with the signature of the original class
public function get_large_image()
{
return $this->large_image;
}
}
Of course, this will get tricky soon, if you don't have the means to control the instantiation of the objects.
$post['obj']->large_image
should do it.
That property is protected so you may not have access unless you are in the class.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.