Adrian
Adrian

Reputation: 2012

How can I access a private variable in a class without changing its visibility

I am wondering is it possible for me to access the _staff_id variable without me having to change the declaration to public (I have access to change this but its not my code and im assuming it was made private for a reason, however i am still tasked with getting this information)

MyObject Object
(

    [_staff_id:private] => 43

)

Upvotes: 0

Views: 101

Answers (1)

Styphon
Styphon

Reputation: 10447

Using a public get function. E.g.:

class MyObject {
    private _staff_id = 43

    public function get($field) {
        return $this->$field;
    }
}
$myObject = new MyObject;
$staff_id = $myObject->get('_staff_id');

This allows you to access the variable without the ability to overwrite its value.

Upvotes: 2

Related Questions