Doubt with method visibility and property in PHP

Asked

Viewed 476 times

2

What is the purpose of declaring functions initiated with underline?

Eventually I wonder why this.

For example:

protected function _exemplo() {}

It is not enough to declare so?

protected function exemplo() {}

Have some other specific reason to declare the function started by underline, when the statement itself already uses the visibility limiter protected?

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

Example (something like that, I just thought):

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 magical method, but it is not!

Example of use in cakephp 2.5 method:

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

    return $results;
}
  • can you link to this code ? (Github)

2 answers

3


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

We used to see many projects with this writing mode, 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 marking.

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

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

//...
protected function hasSomething()
{

Example of use using magical methods and underline:

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 may be able to overload var_dump, implementing the method _var_dump.

  • But from what I understand, it’s only in the statement, and not in the usage, in the same way that we use the protected only in the statement, I am looking at the lib of the cakephp 2.5 framework and use this markup a lot.

  • If you have one statement in one form but use another, you are possibly going through a magic method, for example, checking if there is an internal method starting with underline and delivering the internal if there is one, or handing over the native php if it does not exist. That is, an engineering that allows overload, but is very specific to the object.

  • No, magic methods are two underlines, in this case only one same, as in the above example.

  • how about sending us the github link of this object you are studying ?

  • I posted examples

  • Look at the example I published at the end of the reply

  • It became clearer, but what about the method initiated by double underline? As a magical method? Magic methods are native to php isn’t it? or is it possible to declare a magic method?

  • The method with two underlines, if not magical, concerns a particularity of the project or else, as in the @CIRCLE response, follows an old convention

Show 3 more comments

2

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

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

As @John Conde explains 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 more used at first by PHP programmers and today is not so much used given the significant optimizations that PHP has suffered.

  • Yeah, and that double underscores the property public $__backAssociation = array(); Strange no?

  • @Marcelo updated the answer

  • 2

    Yeah. At first we didn’t have the words of visibility in PHP 4 and semantics were important.

  • exactly, and you’d have to make a lot of comments on the code to keep you in the loop

  • 1

    According to the php manual, this double underline is not recommended to use: "PHP reserves all functions with names starting with __ as magic. It is recommended that you do not use functions with __ names in PHP unless you want some documented magic functionality."

Browser other questions tagged

You are not signed in. Login or sign up in order to post.