了解 PHP 中的类型提示和命名空间


understanding type hinting and namespace in php

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

1.学生.php

2.机构.php

3.注册.php。

我想在enroll类中使用Student and Institution类。我在两堂课上都申请了namespaces Student and Institution。并在注册班级中use它们。但是这里有些不太对劲。我收到这些错误:

警告:具有非复合名称"学生"的 use 语句没有 C:''xampp''htdocs''practice''typehint''enroll.php 在第 2 行的效果

警告:具有非复合名称"Institute"的 use 语句没有 C:''xampp''htdocs''practice''typehint''enroll.php 在第 3 行的效果

致命错误:在 中找不到类"学生" C:''xampp''htdocs''practice''typehint''enroll.php 在第 10 行

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

学生.php

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

研究所.php

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

注册.php

use Student;
use Institute;
  class enroll{
      public function __construct(Student $student,Institute $institute){
         echo $student->name.' enrolled in '.$institute->institute.' school .';
      }
  }
  $student=new Student('zami');
  $institute=new Institute('Government Laboratory High School');
  $enroll=new enroll($student,$institute);

您仍然必须先include其他文件。 否则,PHP 不知道在哪里查找您要查找的命名空间。

注册.php:

<?php
include "student.php";
include "institute.php";
use Student;
use Institute;
  class enroll{
      public function __construct(Student $student,Institute $institute){
         echo $student->name.' enrolled in '.$institute->institute.' school .';
      }
  }
  $student=new Student('zami');
  $institute=new Institute('GLAB');
  $enroll=new enroll($student,$institute);