3

I am looking for the best/correct way to do the following:

myClass::getSomething('stuff');

class myClass
{

    public static function getSomething($var) {

        $obj = new static();
        $obj->var = $var;

        $obj->somethingElse();

    }

    public function somethingElse() {

        // I need to access $obj->var in here

    }

}

Do I pass $obj to somethingElse(), is that the right way?

1
  • 1
    The getSomething method looks like it belongs to a factory. Commented Sep 16, 2016 at 10:03

1 Answer 1

2

$obj is an instance of myClass: It has - among others - a method somethingElse() and you just added a property $var.

So in your method you can access the property directly:

public function somethingElse() {

    $the_contents_of_var = $this->var;

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

3 Comments

I'm clearly having a bad day. I swear I did that and received the error Using $this when not in object context. But I just tried it again and it has worked!! Think I may call it a day...
@superphonic Perhaps you did a self::somethingElse() before, it looks a bit confusing (to me at least...) to have a static method to construct an object in the same class as the object that you are constructing :-)
Well when you put it like that :-)

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.