4

In PHP why can't I do:

class C
{
   function foo() {}
}

new C()->foo();

but I must do:

$v = new C();
$v->foo();

In all languages I can do that...

0

5 Answers 5

16

Starting from PHP 5.4 you can do

(new Foo)->bar();

Before that, it's not possible. See

But you have some some alternatives

Incredibly ugly solution I cannot explain:

end($_ = array(new C))->foo();

Pointless Serialize/Unserialize just to be able to chain

unserialize(serialize(new C))->foo();

Equally pointless approach using Reflection

call_user_func(array(new ReflectionClass('Utils'), 'C'))->foo();

Somewhat more sane approach using Functions as a Factory:

// global function
function Factory($klass) { return new $klass; }
Factory('C')->foo()

// Lambda PHP < 5.3
$Factory = create_function('$klass', 'return new $klass;');
$Factory('C')->foo();

// Lambda PHP > 5.3
$Factory = function($klass) { return new $klass };
$Factory('C')->foo();

Most sane approach using Factory Method Pattern Solution:

class C { public static function create() { return new C; } }
C::create()->foo();
Sign up to request clarification or add additional context in comments.

Comments

8

From PHP 5.4 you CAN do: (new Foo())->someMethod();

Comments

4

In PHP, you can't call an arbitrary method on a freshly created object like new Foo()->someMethod();

Sorry, but that's the way it is.

But you could build a work around like this:

<?php
class CustomConstructor
{
  public static function customConstruct($methodName)
  {
    $obj = new static; //only available in PHP 5.3 or later
    call_user_method($methodName, $obj);
    return $obj;
  }
}

Extend CustomContructor like this:

class YourClass extends CustomConstructor
{
  public function someCoolMethod()
  {
    //cool stuff
  }
}

And instantiate them like this:

$foo = YourClass::customConstruct('someCoolMethod');

I have not tested it but this or something like it should work.

Correction: This will only work in PHP 5.3 and later since late static binding is required.

3 Comments

See the manual section for call_user_method for more about this.
Also PHP 6 will not have that?
I don't know if this issue will be fixed in PHP6. Anyway it's still a long time until 6 comes out.
1

You should not be able to execute code like

new C()->foo();

in other languages, at least not as long as that language accurately follows logic. The object is not just created using C(), but with the full new C(). Therefore, you should hypothetically be able to execute that code if you include another pair of parentheses: (new C())->foo();

(Be warned: I haven't tested the above, I'm just saying it should hypothetically work.)

Most languages (that I've encountered) deal with this situation the same way. C, C#, Java, Delphi...

3 Comments

unfortunately, this doesn't work. php is not c, c#, java, delphi etc.
Hm, odd. I really could have sworn I've done this sort of thing in PHP before. Oh well!
Not true. Based on an operator precedence table new an () are first executed. Also other languages works the same way. So in Java, C#, etc if you do new C().foo() all go fine!
-1

I tried this and was successful -

<?php

$obj = new test("testFunc");

class test{
    function __construct($funcName){
        if(method_exists($this, $funcName)){
            self::$funcName();
        }
    }

    function testFunc(){
        echo "blah";
        return $this;
    }
}

?>

1 Comment

This fails to achieve the chain-ability the asker was intending through the question. Your implementation also requires that the constructor functions parameters be used explicitly for call the chained funciton, which is not what the constructor should be doing.

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.