Doubt with method and property visibility in PHP

2

What is the purpose of declaring functions started underline?

Eventually I wonder why.

For example:

protected function _exemplo() {}

Is not that enough to declare?

protected function exemplo() {}

Is there any other specific reason to declare the function started by underline, when the declaration itself already uses the visibility limiter protected ?

Bonus: If there is another reason, is this restricted to methods or properties?

Example (something like that, just crossed my mind):

protected _$var

Examples of use in properties in CakePHP 2.5:

    protected $_associationKeys = array(
    'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
    'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
    'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
    'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery')
);

/**
 * Holds provided/generated association key names and other data for all associations.
 *
 * @var array
 */
protected $_associations = array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany');

// @codingStandardsIgnoreStart

/**
 * Holds model associations temporarily to allow for dynamic (un)binding.
 *
 * @var array
 */
public $__backAssociation = array();

In the example above, they used 2 underlins as a magic method, but it is not!

Example of method use in cakephp 2.5:

    protected function _findAll($state, $query, $results = array()) {
    if ($state === 'before') {
        return $query;
    }

    return $results;
}
    
asked by anonymous 15.07.2014 / 15:37

2 answers

3

Using underline before a method or a variable is not a general rule, but rather a writing convention that is adopted in a project.

In the past we saw many projects with this type of writing, but nowadays I have not seen good projects adopting standards so, after all, PHP has evolved a lot and we can identify the visibility in many ways without needing this markup.

Imagine if you need to change the visibility of a method? Do you have to rewrite all occurrences? This is not good.

I would particularly adopt lowerCamelCase as the default for variable names and methods, and preferably using common prefixes like get , is , has ...

//...
protected function hasSomething()
{

Example use using magic and underline methods:

class Tools
{
//...

    protected function _foo()
    {
        return 'bar';
    }

    public function __call($name, $arguments = null)
    {
        $method = '_' . $name;
        if (method_exists($this,$method)) {
            //Chamando metodo interno    
            return $this->$method($arguments);
        }

        //Chamando funçao global
        return $name(current($arguments));
    }

}

Output:

$tools = new Tools;
echo $tools->foo(); // bar
$tools->var_dump($_SESSION); //Var dump do array Session

At some point in the future, you can overload var_dump by implementing the _var_dump method.

    
15.07.2014 / 15:45
2

It is in fact a programming convention as it says @group and is used to help identify, in reading a code, which properties and / or methods are private or protected .

Being that:
An underscore _ is used for properties and / or methods protected
Two underscores __ is used for properties and / or methods private

As explained by @John Conde here

For example:

public     $id;
protected  $_name;
private    $__surname;

public function setId(){
    //... Public Access
}

protected function _setName(){
    // ... Protected Access
}

private function __setSurname(){
    // ... Private Access
}

However, as I know, this type of convention was mostly used at the outset by PHP programmers, and today it is not used much anymore given the significant optimizations that PHP has undergone.

    
15.07.2014 / 16:43