Ali Issa Ali Issa - 2 years ago 74
PHP Question

some explanation needed about $this in php?

I am a little confused about something:

I am working on a php project using OOP.

I have a class with a constructor in it like this:

public function __construct(){
$myconnect = new connect();
$this->conn = new PDO('mysql:host=localhost;dbname='. $myconnect->db, $myconnect->user, $myconnect->pass);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

I didn't put
private $conn;
before the class constructor and I was able to use the variable
in my methods like this:
$q = $this->conn->query($sql) or die("failed!");

After noticing that in the example I am following there is a
private $conn;
I was confused why wasn't an error popped up.

Can someone please explain this? and also a little explanation about $this scope will be great.

Answer Source

When you don't define a class property but assign a value to it the first time, it is added to the object as a public property. By setting it explicitly private you lose access to it outside of the object.

Class A {
   public function __construct() {
       $this->foo = 'Hi';

$a = new A();
echo $a->foo; // Outputs 'Hi';

Class B {
   private $bar;
   public function __construct() {
       $this->bar = 'Howdy';   // Accessible only to instances of B

$b = new B();
echo $b->bar;  // Error accessing a private property

This also applies outside any class definition:

$object = new \stdClass();
$object->property = 'abc';    // Automatically public
echo $object->property;       // Outputs 'abc'

Casting an array to an object also creates public properties automatically:

$object = (object) [
    'property' => 'abc'
echo $object->property;       // Outputs 'abc'
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download