簡體   English   中英

為什么 function 作為 php class 中的數組項不起作用

[英]Why function as array item in php class doesn't work

例如,我有這樣一個代碼:

<?php
$A = array(
    'echoSmth' => function(){ 
        echo 'Smth';
    }
);

$A['echoSmth']();  // 'Smth'
?>

它工作正常,但如果 $A 不僅僅是一個變量:而是一個 Class 方法 - 這不起作用:

<?php

class AA {

    public $A = array(
        'echoSmth' => function(){ // Parse Error here!
            echo 'Smth';
        }
    );

}

// Fixed call:
$t = new AA();
$t->A['echoSmth']();
// no matter what call, because error occurs early - in describing of class

?>

為什么它不起作用? 它顯示: Parse error: syntax error, unexpected T_FUNCTION

PS對不起,我在調用方法的方式上犯了一些錯誤,我很着急。 但不管我怎么稱呼。 即使我只聲明 class 而不調用也會發生錯誤

據我所知,在定義 class 成員時,您不能有任何動態,但是您可以如下動態設置它。 所以基本上,你不能這樣做的原因與你不能這樣做的原因相同: public $A = functionname();

另外,您的呼叫簽名不正確,我已在示例中對其進行了修復。

<?php
class AA {
    public $A = array();

    public function __construct() {
        $a = function() {
            echo 'Smth';
        };
        $this->A['echoSmth'] = $a;
    }
}

$t = new AA();
$t->A['echoSmth']();

或者,您可以在__construct()中定義整個數組,其中包含該方法(因此基本上轉換您的代碼)。

我得到了這個工作。 不知道為什么不允許直接聲明。

class AA {
    var $A;
    public function __construct() {
        $this->A = array(
            'echoSmth' => function(){
                echo 'Smth';
            }
        );
    }
}

$t = new AA();
$t->A['echoSmth']();

編輯:我也首先看到並更正$t->$a ,但我還需要移動聲明以使其正常工作。

嗯,它有點工作...

<?php

    class Bleh
    {

        public $f = array();

        public function register( $name , $func )
        {

            $this->f[ $name ] =  $func;

        }

    }   


    $foo = new Bleh;
    $foo->register( 'bar' , function(){ echo 'foobar'; } );

    $foo->f['bar']();

?>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM