【问题标题】:type hinting a class as argument to another class having different namespaces类型提示一个类作为另一个具有不同命名空间的类的参数
【发布时间】:2016-05-22 09:11:27
【问题描述】:

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

1.Student.php

2.机构.php

3.enroll.php.

4.index.php

我想在enroll 类中同时使用Student and Institution 类。我在Student and Institutionenroll 类中应用了namespaces。而use 它们在注册类中。但有些事情并不完全就在这里。我收到以下错误:“它是说我应该通过注册\学生而不是学生\学生”

可捕获的致命错误:参数 1 传递给 注册\注册::__construct() 必须是注册\学生的一个实例, 给定学生\学生的实例,调用 C:\xampp\htdocs\practice\typehint\index.php 在第 9 行并在 C:\xampp\htdocs\practice\typehint\enroll.php 在第 5 行

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

student.php

namespace Student;
 class Student{

     public $name;

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

 }

institute.php

namespace Institute;
   class Institute{

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

enroll.php

   namespace enroll;
      class enroll{

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

index.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);

【问题讨论】:

  • 提醒一下这一行:student.php 中的publci function __construct($value){ 可能希望改为public function...
  • 对不起,我已经更正了它之前..编辑帖子
  • public function __construct(\Student\Student $student,\Institute\Institute $institute){
  • 或者在namespace enroll;之后应用一个use子句,比如use \Student\Student, \Institute\Institute;
  • 将命名空间视为文件夹。如果您尝试在 Institute 文件夹中打开文件 Student,它将无法正常工作。你需要说你想要学生/学生,即学生文件夹中的学生文件,或学生命名空间中的学生类。

标签: php namespaces type-hinting


【解决方案1】:

enroll 类中的构造函数将 Student 和 Institute 类类型提示为属于 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 .';
    }
}

无需加载文件,因为enroll.php文件最后加载到index.php中

【讨论】:

    猜你喜欢
    • 2016-02-06
    • 2012-09-12
    • 2011-03-15
    • 2020-08-11
    • 2011-03-21
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    相关资源
    最近更新 更多