calling a method of an object at instance creation

前端 未结 5 1034
[愿得一人]
[愿得一人] 2020-12-19 18:08

In PHP why can\'t I do:

class C
{
   function foo() {}
}

new C()->foo();

but I must do:

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


        
5条回答
  •  旧时难觅i
    2020-12-19 18:34

    Starting from PHP 5.4 you can do

    (new Foo)->bar();
    

    Before that, it's not possible. See

    • One of many question asking the same on SO
    • Discussion on PHP Internals
    • Another Discussion on PHP Internals
    • Relevant Feature Request in BugTracker

    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();
    

提交回复
热议问题