2015-02-08 71 views
1

我試圖運行Greeter類的$ greeter實例的$ greeter函數屬性。我讀過answers from this related post,但無法讓它們工作(該文章還提到_call,traits,stdClass,從一個函數返回一個函數(這對我來說沒有意義,爲什麼它不需要調用兩次),以及給定的解決方案似乎對我試圖實現的簡單事情來說是過度的)。也許我的情況有點不同。我不明白爲什麼解析器混亂了。將匿名函數賦予屬性的類別:從實例調用賦值函數失敗

class Greeter { 

    private $greeter; 

    function __construct() { 

    $this->greeter = function() { 
     echo "Hello!\n"; 
    }; 

    } 

    public function greet() { 

    $this->greeter(); 

    } 

} 

// THIS WORKS AS EXPECTED: 

$hello = function() { echo "Hi!\n"; }; 
$hello(); 

$greeter = new Greeter(); 

// NEITHER OF THESE WORK: 

call_user_func($greeter->greet); 

$greeter->greet(); 

$greeter['greet'](); 

OUTPUT:

Hi! 

<br /> 
<b>Warning</b>: call_user_func() expects parameter 1 to be a valid callback, no array or string given on line <b>30</b><br /> 
<br /> 
<b>Fatal error</b>: Call to undefined method Greeter::greeter() on line <b>15</b><br /> 

回答

0

OK,所以這個工作,但爲什麼我需要使用call_user_func呢?這是PHP語法的問題,出於某種原因解析器有問題嗎? C++曾經有一個問題,解析<<與嵌套的std::map一起使用,並且有時需要編寫< <來避免該問題。然後引入語法中的一個技巧來解決這個問題。我不明白爲什麼在PHP語法中不可能發生同樣的事情,因此不需要使用call_user_func

class Greeter { 

    private $greeter; 

    function __construct() { 

    $this->greeter = function() { 
     echo "Hello!\n"; 
    }; 

    } 

    public function greet() { 

    call_user_func($this->greeter); 

    } 

} 

// THIS WORKS AS EXPECTED: 

$hello = function() { echo "Hi!\n"; }; 
$hello(); 

$greeter = new Greeter(); 

// NOW THIS ALSO WORKS AS EXPECTED: 

$greeter->greet(); 
1

歡迎來到有趣的PHP。

<?php 
    class A { 
     public function f() { 
      echo 'hi'; 
     } 
    } 

    $a = new A(); 

    $a->f(); // yes 
    call_user_func($a->f); // no $a->f is not a func pointer in PHP 
    call_user_func([$a, 'f']); // yes [$obj, $method_string] is callable 
    $c = [$a, 'f']; 
    $c(); // yes it's a callable 

    [$a, 'f'](); // no PHP don't like that 

    $c = function() use($a) { $a->f(); }; 
    $c(); // yes 

    function() use($a) { $a->f(); }(); // no 
    (function() use($a) { $a->f(); })(); // no 

    // edit: there is more fun I forgot 
    $m = 'f'; 
    $a->$m(); // yes 

    $a->{'greet'}(); // yes 

嗯,這並不容易理解PHP有時在做什麼,但有很多情況下,你不能寫在一個表達式。

empty($this->getNumber())相同或在舊版本中與數組解除引用$this->getArray()[4]

順便說一下,您的意思是在C++模板中關閉>>> >,這些模板被解析爲bitshift運算符,但現在在C++ 11中已經很好了。

+0

是的,我的意思是在C++ 11中修復的'''vs.'>>'。至於你發佈的代碼,它確實表明PHP是一種有趣的語言。 – 2015-02-08 23:23:45