简体   繁体   中英

Class - Function Objects - PHP

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM