2010-05-25 50 views
5

在codeigniter我試圖使用this插件,這需要我在我的模型中實現toString方法。我的toString方法簡單確實php 5.1.6魔法__toString方法

public function __toString() 
{ 
    return (string)$this->name; 
} 

在我的本地機器PHP 5.3一切工作得很好,但用PHP在生產服務器上5.1.6顯示「對象ID#48」裏的那名屬性的值對象應該出現.....我發現了關於problem here的東西,但我仍然不明白...我該如何解決這個問題?

+0

你有沒有試過返回(字符串)$ this-> name? – Galen 2010-05-25 06:05:59

回答

2

升級PHP

我處理同樣的問題,我懷疑你最好的選擇將升級生產服務器上的PHP到>= 5.2.0

在未來(我目前正在學習這種困難的方式),嘗試開發相同的版本,你會部署到。

3

爲了從手動引用:

值得一提的是,PHP 5.2.0之前,當它被直接合並 回聲才被稱爲__toString()的方法或印刷()。由於PHP 5.2.0,它在任何字符串上下文中調用(例如在帶有%s 修飾符的printf()中),但不在其他類型的 上下文中(例如使用%d修飾符)。 自PHP 5.2.0起,將不帶__toString方法的對象 轉換爲字符串 會導致E_RECOVERABLE_ERROR。

我想你已經手動調用了__toString方法,如果你在PHP < 5.2中使用它而不是在echo或print的上下文中。

7
class YourClass 
{ 
    public function __toString() 
    { 
     return $this->name; 
    } 
} 

PHP < 5.2.0

$yourObject = new YourClass(); 
echo $yourObject; // this works 
printf("%s", $yourObject); // this does not call __toString() 
echo 'Hello ' . $yourObject; // this does not call __toString() 
echo 'Hello ' . $yourObject->__toString(); // this works 
echo (string)$yourObject; // this does not call __toString() 

PHP> = 5.2.0

$yourObject = new YourClass(); 
echo $yourObject; // this works 
printf("%s", $yourObject); // this works 
echo 'Hello ' . $yourObject; // this works 
echo 'Hello ' . $yourObject->__toString(); // this works 
echo (string)$yourObject; // this works 
0

您必須爲版本< 5.2明確調用php魔術函數__toString()。所以,你的代碼會變得這樣的事情:

public function myname() 
    { 
     $name = $this->name; 
     return $name.__toString(); //for php versions < 5.2,will also work > 5.2 
    } 

對於版本> 5.2的__toString被自動調用

+2

我懷疑你的意思是'$ name - > __ toString();'。 – 2014-01-24 19:01:53

0

您需要安裝sudo apt install php7.0-mbstring 需要改變PHP版本按你的。

並在此之後不要忘記運行service apache2 restart

希望這會有所幫助。