bernie2436
bernie2436

Reputation: 23911

basic php: why cannot access empty property here?

I am have an instance variable w/ a global scope set in a PHP class. The variable gets set successfully in the constructor. But when I got to access in a getter method I get a PHP fatal error. I'm fairly new to php. Why is $sid not getting set?

class Wrapper
{
    private $sid = null;

    /**

        public function __construct($data){

        // Retrieve client account automatically
        $sid = (isset($data['client_id'])) ? $data['client_id'] : null;
        echo("set sid to");
        echo($sid);
        $this->client = new Account($sid);  //this is getting set properly
       }
       ...
       public function getSID()
       {
               return $this->$sid;
       }

The code that uses the class looks like this (it is a unit test with PHPunit):

public function testGetSubsctions(){
    $clientObject = ClientModel::getInstance(7)->read(); 
    $data = array('client_id' => $clientObject->id);
    $this->assertEquals($data['client_id'], 7);
    $hello = new Wrapper($data);
    $this->assertEquals(7, $hello->getSid());
} 

The code above throws the following error:

Cannot access empty property in /path to/wrapper.php  on line 243

The code on line 242 is getSid, below

public function getSID()
{
    return $this->$sid;
}

Upvotes: 0

Views: 85

Answers (2)

Asenar
Asenar

Reputation: 7020

in the first part of the code you show, we can see return $this->$sid; but $sid is not defined. non-static property has to be called without the $

The correct syntax is :

public function getSID()
{
  return $this->sid;
}

EDIT: see the php documentation for more help on the usage of $this->, static and other things related to OOP in php, and more specifically :

About properties

about static keyword (just for your information to see the difference)

Upvotes: 1

Ibu
Ibu

Reputation: 43830

Here is how you set $sid;

public function __construct($data){

    // Retrieve client account automatically
    $this->sid = (isset($data['client_id'])) ? $data['client_id'] : null;
    echo("set sid to");
    echo($this->sid);
    $this->client = new Account($this->sid);  //this is getting set properly
}

The variable is part of the instance so you have to use the $this keyword. Simply using $sid refers to a new local variable.

And also there is no $ sign before sid:

public function getSID()
{
    return $this->sid;
}

Upvotes: 0

Related Questions