Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use camelCase / Camel Case or underscores in PHP naming?

Tags:

I've been learning PHP and see there is a lot of variability in how people name stuff. I am keen to at least be consistent with myself.

Where should I be using Camel Case and where should I be using underscores?

Thoughts:

  • Variables / Properties: $userid or $user_id or $userID

  • Classes: MyCustomClass or myCustomClass

  • Functions / Methods: my_custom_function() or my_Custom_Function()

Any thoughts appreciated.

like image 697
Linz Darlington Avatar asked Jul 22 '17 12:07

Linz Darlington


People also ask

Is camelCase used in PHP?

PHP owns the top-level namespace but tries to find decent descriptive names and avoid any obvious clashes. Function names use underscores between words, while class names use both the camelCase and PascalCase rules. PHP will prefix any global symbols of an extension with the name of the extension.

When should camel case be used?

CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces. It is commonly used in web URLs, programming and computer naming conventions. It is named after camels because the capital letters resemble the humps on a camel's back.

Should I use camel case or underscore?

Results indicate that camel casing leads to higher accuracy among all subjects regardless of training, and those trained in camel casing are able to recognize identifiers in the camel case style faster than identifiers in the underscore style.

What is the difference between underscore case and camel case?

When multiple words are used to form a variable, camel case joins those words together, without any white space, and delineates the start of each new word with a capital letter. In contrast, snake case uses an underscore between words to create separation.


1 Answers

From the PSR basic coding standard (https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-1-basic-coding-standard.md)

Class names MUST be declared in StudlyCaps (ie: PascalCase).

Class constants MUST be declared in all upper case with underscore separators.

Method names MUST be declared in camelCase.

This guide intentionally avoids any recommendation regarding the use of $StudlyCaps, $camelCase, or $under_score property names.

<?php namespace Vendor\Model;  class Foo {     const VERSION = '1.0';     const DATE_APPROVED = '2012-06-01';      private $StudlyCapsProp = null;     protected $camelCaseProp = null;     public $under_score_prop = null;      public function fooBar()     {      } } 
like image 129
Accountant م Avatar answered Sep 21 '22 13:09

Accountant م