[英]Turning an Object into a string in PHP
我正在 WordPress 站點中創建一個過濾器選項卡。
問題很簡單:它是一個以房地產為主題的網站。 有一份房產清單(一些出售,另一些出租)。
價格使用對象顯示:
$my_property->price()
我希望能夠檢查價格中是否有“每月”一詞,以便能夠知道哪些在出售,哪些在出租。
我可以使用 PHP 中的strstr
函數來做到這一點,但我不能在對象上使用它。
如何將$my_property->price()
的輸出轉換為字符串以能夠操作它並在我的if
語句中使用它?
注意:gettype($my_property) 是 Object 並且 gettype($my_property->price()) 返回帶有 NULL 附加到它的價格。
例子:
// 正常結果 $my_property->price() 將返回示例:$850,000,00
// Gettype 結果 gettype($my_property->price()) 將返回 $850,000,00NULL
$my_property->price()
的輸出是$my_property->price()
的價格。
<header class="entry-header">
<h3 class="entry-title">
<a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
<span class="price"><?php $my_property->price() ?></span>
</h3>
</header>
如果該物業是出租的,則“每月”一詞將顯示在價格旁邊,因此使用這個詞,我將能夠區分哪些物業在出售,哪些物業用於出租。 所以我需要圍繞價格中的Monthly的存在做出一些條件陳述。 我不能做的價格是在對象類型下。 無論如何我可以將這個對象的內容分配給一個新變量,以便我可以嗎? 或者如果有人有其他想法來解決這個問題,那也太棒了。
如果響應是一個字符串,那么您可以執行以下操作:
<?php
$extraClass = '';
$price = $my_property->price();
if (false !== strpos($price, 'Monthly)) {
$extraClass = 'rental';
}
?>
<span class="price <?php $extraClass><"><?php $price ?></span>
或者類似的東西,取決於你為什么真正想要測試租賃。
這就是與顯示價格相關的后端代碼:
/**
* Display property price
*/
public function price() {
if ( ! $this->property_id ) {
return false;
}
echo $this->get_price();
}
/**
* Returns property price
* @return string price
*/
public function get_price() {
if ( ! $this->property_id ) {
return null;
}
$price_amount = doubleval( $this->get_property_meta( $this->meta_keys[ 'price' ] ) );
$price_postfix = $this->get_property_meta( $this->meta_keys[ 'price_postfix' ] );
return $this->format_price( $price_amount, $price_postfix );
}
/**
* Provide formatted price
*
* @param int|double|float $price_amount price amount
* @param string $price_postfix price post fix
* @return null|string formatted price
*/
public static function format_price ( $price_amount, $price_postfix = '' ) {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.