In JAVA you have packages (think namespaces) classes and methods.

This means you can have code which looks something like this

    class myClass{
        public void myMethod(){
            //some code
        }
    }

    myClass myVar = new myClass();
    myVar.myMethod();

Just like PHP there is nothing beyond this structure, you cannot insert a method into myMethod and do something like

myClass.myVar().subMethod();

However you can create a method which returns annother class object like this

    class myReturnableClass{
        public void subMethod(){
            //some code here
        }
    }

    class myClass{
        public myReturnableClass myMethod(){
            myReturnableClass aaa = new myReturnableClass();
            return aaa;
        }
    }

and if you do this the following code works

    myClass myVar = new myClass();
    myVar.myMethod().aaa();

This is sometimes called chaining

My question is simple

Can you do this in PHP?
When using frameworks I have seen code which appears to have more than 2 levels (so do not directly fit in with the class -> method hierarchy but i do not know if this is "chaining" in the way i have just demonstrated or some special addition added by the frameworks.

Comments

Jaypan’s picture

If you return $this from your functions, you can chain them.

Eyal Shalev’s picture

If you define the following classes:

class Bar {
  public function baz() {
    // Do something
    return $this;
  }
}
class Foo {
  public function bar() {
    // Do something
    return new Bar();
  }
}

Then the following chain works.
(new Foo())->bar()->baz()->baz()

P.S.
You have an error in your intro.
in php 5.6 (and in java 8) you can assign an anonymous function (lambda/callable) to a variable and call it as if it was a method.

$hello_printer = function() {
  print 'hello';
};

$hello_printer();