简体   繁体   中英

Variable naming conventions in CakePHP

What is the best way to name variables which contain multiple words? After going through lots of projects available in the CakePHP forge , I have noticed people use either camelCase, underscores or camelCase for variables and underscores for data sent to the view.

An example of the last one would be:

$activeSites = $this->Site->find('all',array('conditions'=>array('Site.active' => '1'), 'recursive' => -1));
$this->controller->set('active_sites', activeSites);

According to the naming conventions used for CakePHP itself ( http://book.cakephp.org/view/509/Coding-Standards#Variables-609 ), variables are named in the following way:

Normal variables should start with a lowercase letter, and should be written in camelBack in case of multiple words.

As most people will tell you, there is not "best way" to name variables, other than to be consistent. Decide the naming convention you like the most, and stick to it. If you're continuing on a project, keep the naming convention that is already there. That is all the advice I can give you.

There isn't a right or wrong answer to this. I usually name it:

$active_sites = $this->Site->find('all',array('conditions'=>array('Site.active' => '1'), 'recursive' => -1));
$this->controller->set('active_sites', $active_sites);

I think any way is fine, but your example showed that the variable in the view and the controller isn't the same. That can be avoided by adopting $active_sites or $activeSites throughout.

(Actually after a while, I start using underscores everywhere.)

Cakephp的创始人使用camelCase风格

Variable names should be as descriptive as possible, but also as short as possible. Normal variables should start with a lowercase letter, and should be written in camelBack? in case of multiple words. Variables containing objects should start with a capital letter, and in some way associate to the class the variable is an object of. Example:

<?php  
     $user = 'John';
     $users = array('John', 'Hans', 'Arne');
     $Dispatcher = new Dispatcher();
?>

Usually you use underscores and only lower case/upper case for labels that are case insensitive. When passed around they may be handled in a case sensitive way.

Case insensitive examples:

  • GET/POST attributes - but on server side they may be handled in a case sensitive way
  • urls - but on server side they may be handled in a case sensitive way
  • filenames on windows - but when transferred to a *nix system they are case sensitive

对于cakePHP应该是camelCase

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM