Jump to content

When should I add $ infront of instance attributes?


eldan88

Recommended Posts

Hey guys.Based from what I know,  when you assign an attribute in a class with a dollar sign in front of it, you can then  call it with out the dollar dollar sign.

 

How come in come I have seen people call the class instance variables with and with out the attribute?

 

 

I understand static attributes are always called with the dollar sign in front of it.  But don't understand how that works with instance variables.

 

Like for example on the database class below, the construct method assigns the construct method with the dollar sign infront of it, and in the get_connection()  return the attribute with out the dollar sign in front of it


Can anyone please explain me why its like that? Thanks

class MySQLDatabase {
    
    private $_connection;
    private static $_instance;
    
    static public function instance() {
        if(!self::$_instance) {
            self::$_instance = new self; 
        }
        return self::$_instance;
    }
    
    
 
    public function __construct() {
        $this->$_connection =  new mysqli('localhost', 'root', 'root', 'sandbox', '8080');
        if($_connection->connect_error) {
            die('Connection Error'.$_connection->connect_error );
        }
    }
    
    
    private function __clone();
    
    public function get_connection() {
        return $this->connection;
    }

Can anyone please explain me why its like that? Thanks

Because they did it wrong. That code is not correct and should yield some errors, namely undefined variable $_connection and trying to get property of non-object.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.