2

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.

7
  • 2
    The bit of code you gave us isn't sufficient for us to help you. Consider adding some real code, or a code that clearly illustrates the problem. Commented Nov 29, 2012 at 17:22
  • That code won't even run. You have no variable in the class called cats. Post real code Commented Nov 29, 2012 at 17:29
  • @nickb No it will fail with an error for a missing property called cats. Or has PHP evolved even further making crappy code that's hard to debug even easier to write? Commented Nov 29, 2012 at 17:31
  • @Cole - No, it runs on practically every PHP version since PHP 4.3.0. Commented Nov 29, 2012 at 17:34
  • @ColeJohnson You can dynamically add properties (they are private by default). This isn't necessarily that crappy, since it PHP tells you on the tin that it is loosely typed. No reason to expect objects to conform to contracts. Commented Nov 29, 2012 at 17:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Hmm, very good idea. That would 100% work, but I have around 20-30 variables in my script.
@user1742590 Added another approach.
Thank you very much for the help! great and fast answer!
1

Define $cats as a public variable in the class:

class cats {
    public $cats;

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

}

1 Comment

Oh wow, such a simple answer. Silly me, I've tried doing searches maybe I wasn't searching it correctly. Thank you, lol I'm an idiot. And I've tried making the function public, public static, ect.. and it's all just as simple as defining the var as public. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.