温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

PHP类型约束是什么

发布时间:2020-10-29 11:40:52 来源:亿速云 阅读:95 作者:小新 栏目:编程语言

PHP类型约束是什么?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。下面是小编给大家带来的参考内容,让我们一起来看看吧!

导语:所谓类型约束,即定义一个变量的时候,必须指定其类型,并且以后该变量也只能存储该类型数据。PHP 虽然是弱类型语言,但是在 PHP 5 已经支持类型约束,包括对象、接口、数组,在 PHP 7 之后支持标量类型约束,下面简单写几个示例。

标量类型、数组

在参数中指明类型,如果不一致,会抛出一个可捕获的致命错误

<?php

/**
 * 数组类型约束
 * @param array $arr
 */
function printArray(array $arr)
{
    echo implode(',', $arr);
}

printArray(array(1, 2, 3));// 1,2,3
printArray('1');// Fatal error: Uncaught TypeError: Argument 1 passed to printArray() must be of the type array, string given, called in D:\WWW\test.php on line 13 and defined in D:\WWW\test.php:7 Stack trace: #0 D:\WWW\test.php(13): printArray('1') #1 {main} thrown in D:\WWW\test.php on line 7

如上所示,标量类型也是如此

<?php

/**
 * 标量类型约束
 * @param string $name
 * @param int $age
 * @param float $height
 * @param bool $isBoy
 */
function sayInfo(string $name, int $age, float $height, bool $isBoy)
{
    echo '姓名:' . $name . ',年龄:' . $age . ',身高:' . $height . ',是否为男孩:' . ($isBoy ? '是' : '否');
}

sayInfo('tom', 12, 134.5, true);// 姓名:tom,年龄:12,身高:134.5,是否为男孩:是

对象、接口

类型约束也可以指定为对象或者接口。首先定义一个 Human 接口,BoyGirl 两个类分别实现接口

<?php

/**
 * 接口
 * Interface Human
 */
interface Human
{
    public function say();

    public function run();
}

/**
 * 实现 Human 接口
 * Class Boy
 */
class Boy implements Human
{
    public function say()
    {
        echo 'a boy say';
    }

    public function run()
    {
        echo 'a boy run';
    }
}

/**
 * 实现 Human 接口
 * Class Girl
 */
class Girl implements Human
{
    public function say()
    {
        echo 'a girl say';
    }

    public function run()
    {
        echo 'a girl run';
    }
}

接下来新建一个类来测试

<?php

include './human.php';

class Action
{
    /**
     * Boy 对象类型约束
     * @param Boy $boy
     */
    public function boySay(Boy $boy)
    {
        $boy->say();
    }

    /**
     * Girl 对象类型约束
     * @param Girl $girl
     */
    public function girlSay(Girl $girl)
    {
        $girl->say();
    }

    /**
     * Human 接口类型约束
     * @param Human $obj
     */
    public function humanRun(Human $obj)
    {
        $obj->run();
    }
}

$obj = new Action();
$obj->boySay(new Boy());// a boy say
echo '<br />';
$obj->girlSay(new Girl());// a girl say
echo '<br />';
$obj->humanRun(new Boy());// a boy run
echo '<br />';
$obj->humanRun(new Girl());// a girl run

当类型约束为具体对象 Boy 或者 Girl 时,只能传入要求的对象。当类型约束为接口 Human 时,可以传入实现接口的类 BoyGirl

感谢各位的阅读!看完上述内容,你们对PHP类型约束是什么大概了解了吗?希望文章内容对大家有所帮助。如果想了解更多相关文章内容,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php
AI