SORU
30 Mayıs 2010, Pazar


Nasıl anında bir php nesne için yeni bir yöntem eklemek için?

Nasıl bir nesne için yeni bir yöntem eklerim "fly"?

$me= new stdClass;
$me->doSomething=function ()
 {
    echo 'I\'ve done something';
 };
$me->doSomething();

//Fatal error: Call to undefined method stdClass::doSomething()

CEVAP
30 Mayıs 2010, Pazar


Bunun için __call koşum:

class Foo
{
    public function __call($method, $args)
    {
        if (isset($this->$method)) {
            $func = $this->$method;
            return call_user_func_array($func, $args);
        }
    }
}

$foo = new Foo();
$foo->bar = function () { echo "Hello, this function is added at runtime"; };
$foo->bar();

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • 8bitdigitaltv

    8bitdigitalt

    31 AĞUSTOS 2011
  • funbro1

    funbro1

    11 Aralık 2007
  • GUN-TIME with Brandon

    GUN-TIME wit

    3 ŞUBAT 2009