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

Linz Darlington picture Linz Darlington · Jul 22, 2017 · Viewed 14.5k times · Source

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.

Answer

Accountant م picture Accountant م · Jul 22, 2017

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()
    {

    }
}