【发布时间】: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 Institution 和enroll 类中应用了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