Exhibitioner
Exhibitioner

Reputation: 123

Most efficient way of accessing a private variable of another class?

There are many methods around that allow you to access private variables of another class, however what is the most efficient way?

For example:

I have this class with some details in:

class something{
    private $details = 
        ['password' => 'stackoverflow',];
}

In another class I need to access them, example (although this obviously wouldn't work since the variable isn't in scope to this class):

class accessSomething{
    public function getSomething(){
        print($something->details['password']);
    }
}

Would a function like this be good enough within the class "something" to be used by the access class?:

public function getSomething($x, $y){
        print $this->$x['$y'];
}   

Upvotes: 1

Views: 151

Answers (1)

DevDonkey
DevDonkey

Reputation: 4880

you should be using proper getters/setters in your classes to allow access to otherwise restricted data.

for example

A class

class AClass {
  private $member_1;
  private $member_2;

  /**
   * @return mixed
   */
  public function getMember1() {
    return $this->member_1;
  }

  /**
   * @param mixed $member_1
   */
  public function setMember1( $member_1 ) {
    $this->member_1 = $member_1;
  }

  /**
   * @return mixed
   */
  public function getMember2() {
    return $this->member_2;
  }

  /**
   * @param mixed $member_2
   */
  public function setMember2( $member_2 ) {
    $this->member_2 = $member_2;
  }

}

which is then called as follows:

$newClass = new AClass();

echo $newClass->getMember1();
echo $newClass->getMember2();

Upvotes: 1

Related Questions