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

I studied PHP and see how people call things diverse. I strive to at least be consistent with myself.

Where should I use Camel Case and where should I use underline?

Thoughts:

  • Variables / Properties: $userideither $user_idor$userID

  • Classes: MyCustomClassormyCustomClass

  • Functions / Methods: my_custom_function()ormy_Custom_Function()

Any thoughts are welcome.

+8
source share
2 answers

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

StudlyCaps.

.

camelCase.

$StudlyCaps, $camelCase $under_score .

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

    }
}
+14

, . , , , . , , - , .

PSR, . , . PSR . , , PSR . , , PHP, , , . , , .

PSR :

  1. , - , , .
  2. . , - .
  3. , , . , , , , .
  4. , , , . .
  5. . - , , , , . Starbucks, Nero Costa , , , , .

, () ().

, ; . , JSON, . , . . .

, , . . , , , , , , . , . , . . , -, , , .

, , , . get_by_username|get_by_email, getByUsername|getByEmail.

(get_by|getBy)($field, $value), , . ucfirst . , __call? , , , lcfirst, , , , , , , . ( ) :

  • lcfirst, , , lcfirst
  • , ucfirst , , concat

Versus:

Snake , , .

- PHP, , . , , , , , .

ifCamelCaseWereReallyThatGreatEveryoneWouldBeAnsweringProgrammingQuestionsOnStackOverFlowLikeThis. asYouCanSeeForAnythingButTheShortestPhrasesShortFormQuicklyBecomesTiring. youCanUsuallyGetAwayWithItInProgrammingAsItsInSmallDosesAndInASeaOfWhiteSpace. anotherAnnoyanceWithCamelCaseIsWhenYouHaveAbbreviationsOrSingleLetterWords. itNotAllGood.

. , , . , , ( PHP). - , , , . , -.

, database_statement_row_read_next() . as Database\Statement::readNextRow .

, . , ( ), -, , , , ..

, , , , . , , , , , , .

, , , , , .

:

  • = alpha_beta
  • = alphaBeta
  • = AlphaBeta

.

, ( ) . , , , PHP, , .

, , .

, , , , , , . , . , , , , -, -, .

:

/:

  • userid , . .
  • user_id .
  • userId
  • userID . user_i_d, user_id.

:

  • MyCustomClass , , .
  • myCustomClass , - , .

/:

  • my_custom_function , ( ), , , function_custom function_default.
  • my_Custom_Function , . , , , .

, . , . , CSV CSV . , . , - , , , . , , , . , , , .

get_by_username|get_by_email. [$operation, $field]. , . , , - . , , getBy_username, deleteBy_username getBy_firstName. , , . snake, , , , , , . , , , , , , .

+4

Source: https://habr.com/ru/post/1682034/


All Articles