örnek yaratılışı bir nesnenin bir yöntemini çağırarak

5 Cevap php

PHP neden yapamam:

class C
{
   function foo() {}
}

new C()->foo();

ama yapmam gerekir:

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

Tüm dillerde bunu yapabilirim ...

5 Cevap

PHP, sizin gibi bir taze oluşturulan nesne üzerinde keyfi bir yöntemi çağırmak olamaz new Foo()->someMethod();

Üzgünüm, ama durum bu yoldur.

Ama böyle bir işi etrafında inşa olabilir:

<?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;
  }
}

Bu gibi CustomContructor uzatın:

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

Ve bu gibi onları örneğini:

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

Ben henüz denemedim ama bu veya bunun gibi bir şey çalışması gerekir.

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

PHP 5.4 itibaren yapaBİLİRSİNİZ: (new Foo())->someMethod();

PHP 5.4 yapabileceğiniz başlangıç

(new Foo)->bar();

Bundan önce, bu mümkün değil. Görmek

Ama bazı bazı alternatifler var

Inanılmaz çirkin çözüm anlatamam:

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

Amaçsız Serialize / unserialize sadece zincirine muktedir

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

Yansıma kullanarak Eşit anlamsız bir yaklaşım

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

Bir fabrika gibi fonksiyonlar kullanarak biraz daha aklı başında bir yaklaşım:

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

Factory Method Pattern Çözüm kullanarak en aklı başında yaklaşım:

class C { public static function create() { return new C; } }
C::create()->foo();

Sen gibi kod çalıştırmak mümkün olmamalı

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

(Uyardı Be: Ben yukarıdaki test değil, sadece should varsayımsal çalışmak söylüyorum.)

(Ben karşılaştı ettik) En diller bu durum ile aynı şekilde anlaşma. C, C #, Java, Delphi ...

Ben bu çalıştı ve başarılı oldu -

<?php

$obj = new test("testFunc");

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

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

?>