Reputation: 25
Say I have this code:
class cats {
function cats_suck() {
$this->cats = "monkeys";
}
}
$cats = new cats;
$cats->cats_suck();
echo $cats->cats; //Monkeys?
I would like to pass $cats
to outside of my class, I would usually just return $cats then echo the function, but I have a lot of variables in my code.
Upvotes: 2
Views: 1577
Reputation:
You could add a getter:
function getcatmonkeys() {
return $this->cats;
}
so then:
$cats = new cats;
$cats->cats_suck();
echo $cats->getcatmonkeys();
Or you could store all privates in an array and add a magic method for getting:
private $data = array();
function cats_suck() {
$this->data['cats'] = "monkeys";
}
public function __get($name)
{
return $this->data[$name];
}
so then:
$cats = new cats;
$cats->cats_suck();
echo $cats->cats; //Monkeys
Which sort of defeats the purpose of having privates, but ours not to question why.
Upvotes: 2
Reputation: 637
Define $cats as a public variable in the class:
class cats {
public $cats;
function cats_suck() {
$this->cats = "monkeys";
}
}
Upvotes: 1