1

I noticed on magento, they call a function which is referenced as an object like:

className::function('example')->example;

Which to me makes no sense how it works? I tried to mimic this inside a test file but I get nothing.

<?php

class Example
{

    public function test($arg)
    {
        $want = new ExampleTwo;
        return 1;
    }

}

class ExampleTwo
{
    public $want;
    public function urgh($arg)
    {
        $this->want = "returnn";
    }
}

$Obj = new Example;
echo $Obj->test('random')->want;

NOTICE Trying to get property of non-object on line number 24

Can anyone please explain how the function becomes an Object? and if so, how can I then get values from the function object.

1
  • Function needs to return an object not a string Commented Mar 17, 2016 at 13:07

1 Answer 1

3

If you return an object in a function, you can call that object directly from the function returned value.

In your test case:

public function test($arg)
{
    $want = new ExampleTwo;
    return $want;
}

If you have this:

$Obj = new Example;
echo $Obj->test('random')->want

This will echo the "want" property of the ExampleTwo class, which will be NULL in your example code.

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

2 Comments

Wow, that actually makes more sense, I actually didn't know you could do this? That's awesome, you can even add functions and call functions ->anotherTest('?')->andAnother('ssss'); thats mad
this adds a whole new dimension to object orientated programming :o Appreciated!

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.