[英]How to get the items inside an array in Object Oriented PHP?
我在視圖中有以下變量:
$recent_posts
它是一個數組,所以我在它上面執行了一個foreach循環,var像這樣拋出了結果:
<? foreach($recent_posts as $post): ?>
<pre><?= var_dump($post) ?></pre>
<? endforeach ?>
這是我從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] =>
)
)
如何檢索每個帖子的值。 例如,如何獲取帖子的large_image
? 我試過這個(不知道我在做什么),並不奇怪它不起作用:
<?= $post->large_image ?>
large_image
protected
,您無法訪問類的protected
members
( this
上下文)。
您有兩個選項,為large_image
添加getter
函數或將其public
。
getter
是一個公開private
或protected
成員的函數
public function get_large_image(){
return $this->large_image;
}
由於$post->large_image
是受保護的屬性,因此不允許在類(或派生類)之外訪問它。 我假設可能有一個getter方法,你可以通過它來檢索值get_large_image()
或許像get_large_image()
)。
要確定對象上可用的方法,請查看附帶類的源代碼,或使用反射:
$refl = new ReflectionClass( $post );
var_dump( $refl->getMethods() );
如果沒有可用的方法來獲取值,我不會建議你改變類,通過使屬性公開(由於我認為的原因而被保護),或者根本不改變類,如果它不是你自己的。
相反,如果可能的話,我建議你擴展類並為值創建一個getter方法:
<?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;
}
}
當然,如果你沒有辦法控制對象的實例化,這很快就會變得棘手。
$post['obj']->large_image
應該這樣做。
該屬性受到保護,因此除非您在課堂上,否則您可能無法訪問該屬性。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.