简体   繁体   English

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

[英]understanding type hinting and namespace in php

i don't have much intuitive knowledge on type hinting and namespaces. 我对类型提示和名称空间没有很多直觉的知识。 So i made up the following code to work with both of the concepts.I have three php pages holding three classes inside same directory.They are-- 因此,我组成了以下代码以同时使用这两个概念。我有三个php页面,它们在同一目录中包含三个类。

1.Student.php 1.Student.php

2.Institution.php 2.Institution.php

3.enroll.php. 3.enroll.php。

i want to use both the Student and Institution class inside the enroll class.I applied namespaces in both Student and Institution class.And use them inside enroll class.But something isn't quite right here.I am getting these errors: 我想在enroll类中同时使用Student and Institution类。我在Student and Institution类中都应用了namespacesStudent and Institution在enroll类中use它们。但是这里有些不正确。

Warning: The use statement with non-compound name 'Student' has no effect in C:\\xampp\\htdocs\\practice\\typehint\\enroll.php on line 2 警告:第2行的C:\\ xampp \\ htdocs \\ practice \\ typehint \\ enroll.php中具有非化合物名称'Student'的use语句无效

Warning: The use statement with non-compound name 'Institute' has no effect in C:\\xampp\\htdocs\\practice\\typehint\\enroll.php on line 3 警告:非复合名称“ Institute”的use语句在第3行的C:\\ xampp \\ htdocs \\ practice \\ typehint \\ enroll.php中无效

Fatal error: Class 'Student' not found in C:\\xampp\\htdocs\\practice\\typehint\\enroll.php on line 10 致命错误:在第10行的C:\\ xampp \\ htdocs \\ practice \\ typehint \\ enroll.php中找不到类'Student'

can anyone explain what is wrong here and how i can fix this ? 谁能解释这是什么问题,我该如何解决?

student.php student.php

namespace Student;
 class Student{

     public $name;

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

 }

institute.php Institute.php

namespace Institute;
   class Institute{

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

enroll.php enroll.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);

You still have to include the other files first. 您仍然必须首先include其他文件。 otherwise, PHP doesn't know where to look for the namespaces you are looking for. 否则,PHP不知道在哪里寻找您要寻找的名称空间。

enroll.php: enroll.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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM