Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

php - calling a method of an object at instance creation

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...

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...