user1742590
user1742590

Reputation: 25

Passing variable from function within class & echo outside of class

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

Answers (2)

user1726343
user1726343

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

abegosum
abegosum

Reputation: 637

Define $cats as a public variable in the class:

class cats {
    public $cats;

    function cats_suck() {
        $this->cats = "monkeys";
    }

}

Upvotes: 1

Related Questions