I’ve implemented a simple palindrome problem in a CakePHP application to learn the language and framework. I have everything working, but there is one bit of odd behavior that I haven’t been able to explain.
I have a class called Palindrome with a __construct method, which accepts one parameter, which should always be a string. However, the first time I instantiate an instance of the Palindrome class, the __construct method is executed twice, and the first time time an array is passed in that appears to be some reference to the class. I’ve been able to work around this, but I don’t understand why it is happening. Can anyone enlighten me? Here is my code:
The class file:
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);
}
}
}
The controller:
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);
}
}
Input “foo\nbar\nbaz” generates this output –
---> foo
==> Array
==> FOO
---> bar
==> BAR
---> baz
==> BAZ
This is CakePHP 2.2.3 with PHP 5.3.15.
You have
new $this->Palindrome(...)From the controller
$this->Modelacts kind of like a singleton. It is created automatically then you can use it several time to read/write data to your datasource. For example, the same Model object is used through this whole block of code: