开发者

How to get the items inside an array in Object Oriented PHP?

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_imag开发者_如何学Ce ?>


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜