簡體   English   中英

如何使用可選參數鍵入PHP函數

[英]How to type-infer PHP-functions with optional arguments

PHP的問題是,使用帶有可選參數的函數時,它沒有特定的語法。 這個:

foo(10);

可以是這個嗎

function foo($a) {}

或這個

function foo($a = 0) {}

或這個

function foo($a, $b = 0, ...) {}

(甚至function foo() {} ,但暫時不考慮它)。

那么,在定義函數之前使用函數時,如何進行類型推斷呢?

一種解決方案是記錄所有用法,直到定義出現,然后查看它們是否都可以與之統一。 然后,上面的示例將存儲

int -> unit

然后檢查它是否與

int -> (typ list) -> unit

或其他任何內容(其中typ list是可選參數的列表)。

您認為這可行嗎? 還有其他常規方法可以解決此問題嗎?

我不知道這在多大程度上可以回答您的問題,但是要詳細說明我在上面的評論,您可以使用PHP的內置反射類套件來幫助內省和獲取有關函數及其參數的有用信息。

具體來說,我認為ReflectionFunctionReflectionParameter在您的情況下可能會有用,盡管還有很多功能可能會有所幫助。

例如,這是一個非常簡單的示例,您想在其中獲得有關函數參數的一些信息:

<?php

// a simple function with an
// optional/default argument
function foo($a, $b = 0)
{
    return $a + $b;
}

// create a ReflectionFunction object
// passing the name of the function name.
// you can also pass a variable reference 
// to an anonymous function.
$refl = new ReflectionFunction('foo');

// iterate over the ReflectionFunction's
// parameter list to get a ReflectionParameter
// object for each of foo's arguments. here we're 
// just printing out a __toString() summary of each
// argument.
foreach ($refl->getParameters() as $param) {
    echo $param . PHP_EOL;
}

產量:

Parameter #0 [ <required> $a ]
Parameter #1 [ <optional> $b = 0 ]

如您所見,這個簡單的示例顯示了有關foo的參數列表的一些信息:參數編號,必需/可選,變量名和默認值。

$paramReflectionParameter一個實例,因此可以調用一堆方法來獲取有關每個參數的更多信息,包括:

export
__construct
__toString
getName
isPassedByReference
canBePassedByValue
getDeclaringFunction
getDeclaringClass
getClass
isArray
isCallable
allowsNull
getPosition
isOptional
isDefaultValueAvailable
getDefaultValue
isDefaultValueConstant
getDefaultValueConstantName

希望這可以幫助! :)

您可能必須插入“弱”類型變量並保留它們,直到找到函數定義為止,或者首先構建完整的AST,然后通過類型推斷對其進行運行,如果存在定義不明的函數,則會引發錯誤(我想知道您如何處理內置函數,也許使用預烘焙的類型簽名數據庫?)。

暫無
暫無

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

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