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']; } 
2
  • 2
    You may want to take a look at this : getter and setter Commented Jul 14, 2015 at 13:43
  • The question is probably too broad to be reasonably answered. When we're done with the multitude of yesreasons and the multitude of no reasons there are still the myriads of opinions and styles ;-) Commented Jul 14, 2015 at 13:46

1 Answer 1

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(); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.