tags:

views:

56

answers:

2

Considering this PHP example:

class A
{
  public function getB( )
  {
    return new B();
  }
}

class B
{
  public function test( )
  {
    echo "Hello";
  }
}

I could use this:

$a = new A( );
$b = $a->getB( );
$b->test( ); // Hello

Or this:

$a = new A();
$a->getB( )->test( ); // Hello

Taking a closer look at the second example...

  • What is the name of this form of expression?
  • Does this have something to do with dereferencing?

  • In which programming languages is this available?

  • What other forms of this exist?
+2  A: 

It's called method chaining, and you can see it in a lot of languages. It's not exactly dereferencing; each method call returns an object, which the next method takes as the active object. This is a pretty familiar concept in PHP and JavaScript (think jQuery) and a lot of languages, each with it's own idiom for the call.

sczizzo
i don't think this is called "method chaining", see Fowler's definition: http://martinfowler.com/dslwip/MethodChaining.html
stereofrog
+1  A: 

When dealing with objects the dereferencing operator is used to access an object from the name of the object. In the example you gave -> is the dereferencing operator so you are using dereferencing in the example.

The first example is creating an explicitly named object, you are naming it $b. In the second example you are also creating the object but you are not naming it, you are using it anonymously. But in both cases you are creating an object and accessing it via a dereferencing operator.

This type of statements are available in all object oriented languages.

Vincent Ramdhanie