【发布时间】:2018-08-25 05:11:36
【问题描述】:
我有一个函数应该接受一个数组,或者一个字符串和另一个字符串。其他操作数类型将被拒绝。
我该怎么做?
【问题讨论】:
-
检查我的回答,如果它有助于解决您的问题,请标记为已接受。如果您还有任何问题,请告诉我。
标签: php function extend operands
我有一个函数应该接受一个数组,或者一个字符串和另一个字符串。其他操作数类型将被拒绝。
我该怎么做?
【问题讨论】:
标签: php function extend operands
您可以将您的函数定义为只接受数组或字符串,如果找到另一个操作数,它将自动退出 php 函数。
以下只是 PHP 脚本,您可以手动将其识别到您的 PHP 函数中。
PHP 函数示例:
function testStringAndArray($arg) {
if(is_array($arg)|| is_string($arg)) {
//Do Processing
} else {
return false;
}
}
【讨论】:
false
您可以使用 php 的 is_array() 函数来检查给定的选项是否在数组或字符串中。
【讨论】:
【讨论】:
false
false。现在//do something here 也可能返回false。如何区分?一种方法是抛出异常(不检查异常)。
// do something只是程序员可以写一些事情的声明。
带有“无参数”、字符串参数和数组参数的附加功能示例。
<?php
class Speaker {
public function sayHello($person = null)
{
// I will display hello something base on parameter type.
$this->render(
$this->prepareParams($person);
);
}
private function prepareParams($param = null) {
//Default value
if(is_null($param)) {
$param = 'World';
}
else if(is_array($param)) {
//Merge all item to one string with coma separator
$param = implode(', ', $param);
}
return $param;
}
private function render(string $target) {
echo "Hello ".$target;
}
}
$tester = new Speaker();
$this->sayHello();
$this->sayHello('Yanis');
$this->sayHello(['Yanis', 'thomas','roman']);
您可以处理默认参数来管理您的第二个可选参数,例如:
if(!is_null($mySecondParameter)) // I can use it Because he is defined.
【讨论】:
好吧,我只是想得太复杂了。 我想要类似的东西
public myFunction(array $arg1) {
...
}
public myFunction(string $arg1, string $arg2) extends myFunction {
...
}
但是使用类似的东西会容易得多
public myFunction($arg1, $arg2 = null) {
if(is_array($arg1)) {
...
}
if(is_string($arg1) && is_string($arg2)) {
...
}
【讨论】: