簡體   English   中英

您如何稱呼該功能,即您可以在Python中將變量分配給函數,然后將參數傳遞給該變量?

[英]what do you call the feature where you can assign a variable to a function in Python then pass arguments to that variable?

您將Python的功能稱為什么:

  1. 您將函數分配給變量

    myPowerVariable =戰俘

    mySqrtVariable = math.sqrt

  2. 然后用參數調用該變量?

    myPowerVariable(2,3)

    prints 8

    mySqrtVariable(9)

    prints 3

如果您在PHP中嘗試使用該功能,將無法正常工作,希望有人可以告訴我該功能的名稱。

謝謝

首先,您會混淆措辭:實際上是將函數分配給變量

無論如何,這是具有一流功能的Python的示例。

在PHP中,假設您使用正確的PHP語法,它們被稱為Variable函數並且可以正常工作:

$myPowerVariable = 'pow';
echo $myPowerVariable(2, 3);  // prints 8

如果您這樣做:

$myPowerVariable = pow();

你得到:

警告:pow()恰好需要2個參數,給定0個

因為您正在執行pow()並將結果分配給$myPowerVariable但是沒有提供所需的參數。

這是您在注釋中提到的Anonymous函數的簡單示例:

$myPowerVariable = function($a, $b) {
    echo pow($a, $b);
};

$myPowerVariable(2, 3);

通常將其稱為函數編程 ,並且該功能確實存在於PHP中,盡管語法有所不同。 以下在PHP中有效:

function myFunction() {
    echo 'here!';
}

$myVar = 'myFunction';

$myVar();

這在PHP中也適用:

class myClass
{
    function myMethod() {
        echo 'here!';
    }
}

$myVariable = ['myClass', 'myMethod'];

call_user_func($myVariable);

暫無
暫無

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

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