2013-08-22 20 views
0

我很好奇在PHP OOP中編寫鏈接接口。我從php.net網站修改了這個示例代碼,我想進一步說明 - 我怎樣才能從這種接口返回對象或數組?如何從PHP OOP中的鏈接接口返回對象或數組?

// Declare a simple class 
class TestClass 
{ 
    public $foo; 

    public function __construct($foo) 
    { 
     $this->foo = $foo; 
    } 

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

$input = (object)array("title" => "page 1"); 
$class = new TestClass($input); 
echo $class; 

錯誤,

Catchable fatal error: Method TestClass::__toString() must return a string value in C:\wamp\www\test\2013\php\fluent_interface.php on line 2

我應該使用不同的魔術方法,而不是__toString呢?

編輯: 我能回到這是我的結果,

stdClass Object ([title] => page 1) 
+0

你究竟想要做什麼? – Dragony

+0

請參閱我上面的修改。謝謝。 – laukok

回答

1

爲了得到你想要的,你需要使用下面的語法:

print_r($class->foo); 

的__toString()魔術方法嘗試將您的整個類'TestClass'轉換爲字符串,但由於魔術方法沒有返回字符串,它會向您顯示該錯誤。當然,你也可以重寫你的__toString()方法來做到以下幾點:

public function __toString() 
{ 
    return print_r($this->foo, true); 
} 

http://php.net/manual/en/function.print-r.php

http://www.php.net/manual/en/language.oop5.magic.php#object.tostring

+0

感謝您的答案。 – laukok

+0

但似乎我無法訪問該對象內的屬性,例如,'$ class = new TestClass($ input); echo $ class-> title;'我得到這個錯誤'注意:未定義的屬性:TestClass :: $ title在C:... fluent_interface.php在第23行而不是在第1頁...我怎樣才能訪問對象內部的數據呢? – laukok

+1

您的類中的foo屬性包含另一個對象,即您的數據。在你的例子中,你應該使用這個語法:$ class-> foo-> title – Dragony

1

我認爲你正在尋找要麼print_rvar_export功能:

public function __toString() 
{ 
    return var_export($this->foo, true); 
} 

和var_export更好,因爲它也返回值的類型(並且,除此之外,有效的P HP代碼格式)。請注意,__toString()方法與流暢的接口沒有任何共同之處。這只是不同的事情。

+0

謝謝但我怎麼才能訪問返回對象內的數據呢?例如'echo $ class-> title;'我想得到'page 1'作爲結果。可能嗎? – laukok

+0

我不確定你想達到什麼目的。用那些傳遞給構造函數的類來替換你的類實例?如果是,爲什麼? –

+0

對不起,我通過這樣做了'echo $ class-> foo-> title;'謝謝你的幫助。 – laukok