php函数定义参数类型,PHP函数定义某个参数类型为多种

原文:

Is it possible to define a function argument as multiple possible types? For example, a function may take a string or an integer to accomplish something. Is it possible to somehow define it like this?

function something(int|string $token) {}

Or is only one type per argument supported?

(mind you, I know I can filter input later on, I just like to have my arguments typed)

# Answer 1

4d350fd91e33782268f371d7edaa8a76.png

The best you can do is called Type Hinting and is explained here:

In particular, you can hint a class type or an array type, but (as the manual says) "Traditional type hinting with int and string isn't supported." So I guess that what you are trying to accomplish is not possible at this level.

However, you can create your own wrappers, etc. There are probably a thousand ways to handle this.

# Answer 2

No, it is not possible.

Also, type hinting in PHP 5 is now only for classes and arrays. http://php.net/manual/en/language.oop5.typehinting.php

class Foo

{

}

function something(Foo $Object){}

# Answer 3

PHP is dynamically typed - but type hinting has been added to the language - so if you've not hinted the parameter you can pass any type you like:

function something($token)

{

if (is_numeric($token)) {

// its a float, double, integer

} else {

// its a string, array, object

}

}

(off the top of my head I'm not sure how resources are handled).

However if you want to program in a strongly typed language, then (IMHO) you should be using something other than PHP

# Answer 4

2020 Update:

Union types have finally been implemented in PHP 8.0, which is due for release near the end of 2020.

They can be used like this:

class Number {

private int|float $number;

public function setNumber(int|float $number): void {

$this->number = $number;

}

public function getNumber(): int|float {

return $this->number;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值