0
我在CakePHP應用程序中實現了一個簡單的迴文問題來學習語言和框架。我有一切工作,但有一點奇怪的行爲,我無法解釋。用數組執行CakePHP __construct
我有一個叫做Palindrome的類,帶有一個__construct方法,它接受一個參數,它總是一個字符串。但是,當我第一次實例化一個Palindrome類的實例時,__construct方法會執行兩次,並且在第一次傳入數組時,這似乎是對類的一些引用。我已經能夠解決這個問題,但我不明白爲什麼會發生。任何人都可以啓發我嗎?這裏是我的代碼:
類文件:
class Palindrome {
public $base_string = "";
public function __construct($passed_string)
{
print "==> $passed_string<br />";
if(!is_array($passed_string))
{
$this->base_string = trim($passed_string);
}
}
}
控制器:
class PalindromesController extends AppController
{
public $helpers = array('Html', 'Form');
public function index()
{
}
public function test_strings()
{
$string_array = explode("\n", $_POST["text_to_test"]);
$string_index = 0;
$palindrome_array = array();
while($string_index < count($string_array))
{
$my_string = $string_array[$string_index];
print "---> $lcString<br />";
array_push($palindrome_array, new $this->Palindrome(strtoupper($my_string)));
$string_index = $string_index + 1;
}
$this->set("palindrome_array", $palindrome_array);
}
}
輸入 「富\ NBAR \ nbaz」 生成的輸出 -
---> foo
==> Array
==> FOO
---> bar
==> BAR
---> baz
==> BAZ
這是PHP 5.3.15的CakePHP 2.2.3。
謝謝,這很有道理。所以現在我的問題是,我應該這樣做嗎?在構造函數中測試參數以防止出現錯誤似乎非常困難,但我一直無法找到一個好的選擇。或者我只是誤解了一些基本的東西?如果它很重要,這不是一個「模型」,只是一個常規類,其唯一目的是封裝類似的功能(數據庫中沒有「palindromes」表)。 –
迴文聽起來更像是一個圖書館類。你應該移動(http://book.cakephp.org/2.0/en/getting-started/cakephp-folder-structure.html)代碼和加載(http://book.cakephp.org/2.0/en/core -utility-libraries/app.html)。 –
這很好,謝謝。 –