类型暗示一个类作为具有不同命名空间的另一个类的参数


type hinting a class as argument to another class having different namespaces

我对类型提示和命名空间没有太多直观的了解。因此,我编写了以下代码来处理这两个概念。我有三个php页面,在同一目录中包含三个类和一个索引.php文件。他们是——

1.学生.php

2.机构.php

3.注册.php。

4.索引.php

我想在enroll类中使用Student and Institution类。我在Student and Institutionenroll班上申请了namespaces。并在注册班级中use它们。但是这里有些不太对劲。我收到这些错误:">它说我应该通过注册''学生而不是学生''学生">

可捕获的致命错误:参数 1 传递给 enroll''enroll::__construct(( 必须是 enroll''Student 的实例, 给定的学生''学生实例,调用 C:''xampp''htdocs''practice''typehint''index.php 在第 9 行,定义于 C:''xampp''htdocs''practice''typehint''enroll.php 在第 5 行

谁能解释一下这里出了什么问题以及我如何解决这个问题?

学生.php

namespace Student;
 class Student{
     public $name;
     public function __construct($value){
        $this->name=$value;
     }
 }

研究所.php

namespace Institute;
   class Institute{
      public $institute;
      public function __construct($val){
         $this->institute=$val;
      }
   }

注册.php

   namespace enroll;
      class enroll{
          public function __construct(Student $student,Institute $institute){
             echo $student->name.' enrolled in '.$institute->institute.' school .';
          }
      }

索引.php:

include 'institute.php';
include 'student.php';
include 'enroll.php';
  $institute=new institute'institute('GLAB');
  $student=new student'student('zami');
  $enroll=new enroll'enroll($student,$institute);

注册类中的构造函数将学生类和学院类键入为属于注册命名空间,这就是错误的原因。为了从学生和学院命名空间键入提示类,您只需要使用它们:

注册.php

namespace enroll;
use Student'Student;
use Institute'Institute;
class enroll{
    public function __construct(Student $student,Institute $institute){
        echo $student->name.' enrolled in '.$institute->institute.' school .';
    }
}

无需加载文件,因为注册.php文件在索引中最后加载.php