1

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'];
}   
Exhibitioner
  • 123
  • 11
  • 2
    You may want to take a look at this : [getter and setter](http://stackoverflow.com/questions/4478661/getter-and-setter) – VDarricau Jul 14 '15 at 13:43
  • The question is probably too broad to be reasonably answered. When we're done with the multitude of `yes`reasons and the multitude of `no` reasons there are still the myriads of opinions and styles ;-) – VolkerK Jul 14 '15 at 13:46

1 Answers1

1

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();
DevDonkey
  • 4,835
  • 2
  • 27
  • 41