Trick with variable name transformation in CakePHP

CakePHP is a good PHP MVC framework. You can study it easily and start developing web sites very fast. But it has some disadvantages, of course. One of them is strange rules for transformation variable name when it set in the controller. Statement

$my_var = 'Hello world!';
$this->set('my_var', $my_var);

will make the variable $my_var accessible in your view:
<?php echo $my_var; ?>
The phrase ‘Hello world!’ should appear on the web page. But if the same operation is done using function compact, the result is not predictable:
$my_var = 'Hello world!';
$this->set(compact('my_var'));

Instead of ‘Hello world!’ you’ll see the warning about undefined variable on your web page. It happens because cakePHP removes underscore and makes letter, followed by it, capital. So, instead of $my_var you should use $myVar in the view:
<?php echo $myVar; ?>

Note that this bug appears in the cakePHP version 1.2. It’s already fixed in the 1.3.

Published by

Michael Stepanov

Site owner and admin :)

Leave a Reply

Your email address will not be published. Required fields are marked *