tags:

views:

77

answers:

4

I know that underscores in function names in PHP is used to "implicitly" denote that they are supposed to be private...but I just saw this code:

class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }

  private $_handle = null;

  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }

  public function handle()
  {
    return $this->_handle;
  }
}

print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );

in this code, what does it mean to have underscores in variables?

+5  A: 

It's kind of the same for methods and properties : the convention is the same : having a name that starts by one underscore generally means they are to be considered as private/protected.

(Of course, it's not the same with methods which have a name that starts by two underscore : those are magic methods, and two underscore should not be used for your "normal" method names)

Pascal MARTIN
A: 

Ahh __construct is a special method. It is PHP way of saying that is the constructor. They stole that from Python probably where those are magic methods.

When a class is instantiated the constructor is called automatically.

so if you create the object myconnection = DatabaseConnection() it will automatically call:

$dsn = 'mysql://root:password@localhost/photos';
$this->_handle =& DB::Connect( $dsn, array() );

... the code in the constructor. So then when you call get() later (be careful it is static) it will have a connection.

I sometimes move that code into a different method, say connect() and call that in the constructor, so I can do it either way. I imagine the real thing that is tripping you up is the 'static' method get. Those do not require a fully constructed object to be called.

brianray
+1  A: 

The convention is usually this:

  • one underscore is usually used for protected/private methods and variables, so that they stick out
  • two underscores are reserved for "magic" methods like __construct, __get, __set etc. which have special meaning in the language, so you should not use it unless you writing a known magic method.

This said, the language does not assign any special meaning to one-underscore names, it's just a convention - so you don't have to make it private, and some people with backgrounds in other languages for example mark all properties with underscore to distinguish them from methods.

StasM
A: 

Properties (variables) have visibility just like methods (functions).

Álvaro G. Vicario