3

我知道 PHP 是一种非常容错的语言,我想这就是为什么你可以为函数调用使用混合变量,例如:

/**
 * @param mixed $bar
 **/
function foo($bar) {
    // Do something with $bar, but check it's type!
}

是否有使用此类混合变量的推荐方法?

对于我自己的项目,我尽量避免这种混合变量,只是为了减少以后的错误问题和代码的清晰度。

在 PHP 7 中,应该可以声明这个函数期望的变量类型,不是吗?这是怎么做到的?

4

2 回答 2

2

这可能很快成为一个意见问题,但是,我觉得松散的类型会引入更多发生错误的可能性。可能在某些情况下它是合适的,但通常,对于需要可靠和可维护的代码(可能高于“灵活”),严格类型更安全。

PHP 5 有“类型提示”:

从 PHP 5.0 开始,您可以使用类或接口名称作为类型提示,或者self

<?php
function testFunction(User $user) {
    // `$user` must be a User() object.
}

从 PHP 5.1 开始,您还可以将array其用作类型提示:

<?php
function getSortedArray(array $array) {
    // $user must be an array
}

PHP 5.4 添加callable了函数/闭包。

<?php
function openWithCallback(callable $callback) {
    // $callback must be an callable/function
}

从 PHP 7.0 开始,也可以使用标量类型int( , string, bool, float):

<?php
function addToLedger(string $item, int $quantity, bool $confirmed, float $price) {
    ...
}

从 PHP 7 开始,这现在称为类型声明

PHP 7 还引入了返回类型声明,允许您指定函数返回的类型。此函数必须返回一个float

<?php
function sum($a, $b): float {
    return $a + $b;
}

如果您不使用 PHP7,则可以使用可用的类型提示,并使用适当的PHPDoc 文档填补剩余的空白:

<?php

/**
 * Generates a random string of the specified length, composed of upper-
 * and lower-case letters and numbers.
 *
 * @param int $length Number of characters to return.
 * @return string Random string of $length characters.
 */
public function generateRandomString($length)
{
    // ...

    return $randomString;
}

许多编辑器可以解析这些注释并警告您输入不当(例如 PHPStorm)。

于 2016-05-30T10:14:31.550 回答
2

这可能会因为“基于意见”而被关闭,但这仍然是一个好问题。

一个函数应该做一件事。如果您需要这样做:

if it's a string
    do this
else if it's a Foo object
    do this other thing

那么它做的不止一件事,就是“不太理想”的形式。

你为什么不直接提供两个有名的方法,例如:getThingById(int)and getThingByFilters(Filters)or getThingLike(string)etc?它也会使您的代码更具可读性和可预测性。

于 2016-05-30T10:34:46.990 回答