首页 > 解决方案 > PHP 7 致命错误:未捕获的 TypeError:传递给 Some2::send() 的参数 1 必须是 Path\To 的实例,Path\To\Some 的实例

问题描述

我有 3 个 .php 文件:some_class.php、some2_class.php 和 index.php

some_class.php

<?php
namespace Path\To;

class Some {
    public $id;
    public function __construct() {
        $this -> id = 2021;
    }
}

some2_class.php

<?php
class Some2 {
    public function send(\Path\To $some)
    {
        
    }
}

索引.php

require_once('some_class.php');
require_once('some2_class.php');

$c = new Path\To\Some();

$c2 = new Some2();
$c2 -> send($c);

当执行 index.php 我看到:

致命错误:未捕获的 TypeError:传递给 Some2::send() 的参数 1 必须是 Path\To 的实例,Path\To\Some 的实例,在 /home/l/liketeks/work/public_html/index.php 中调用在第 8 行并在 /home/l/liketeks/work/public_html/some2_class.php:3 中定义 堆栈跟踪:#0 /home/l/liketeks/work/public_html/index.php(8): Some2->send( Object(Path\To\Some)) #1 {main} 在第 3 行的 /home/l/liketeks/work/public_html/some2_class.php 中抛出

标签: php

解决方案


我认为您缺少类型提示的完整路径。不应该是:

class Some2 {
    public function send(\Path\To\Some $some)
    {
        
    }
}

推荐阅读