【问题标题】:understanding type hinting and namespace in php理解 php 中的类型提示和命名空间
【发布时间】:2016-05-22 07:07:10
【问题描述】:

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

1.Student.php

2.机构.php

3.enroll.php.

我想在enroll 类中同时使用Student and Institution 类。我在Student and Institution 类中应用了namespaces。而use 它们在注册类中。但是这里有些不太对劲。我收到这些错误:

警告:非复合名称“Student”的 use 语句没有 在第 2 行的 C:\xampp\htdocs\practice\typehint\enroll.php 中的效果

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

致命错误:未找到班级“学生” C:\xampp\htdocs\practice\typehint\enroll.php 在第 10 行

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

student.php

namespace Student;
 class Student{

     public $name;

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

 }

institute.php

namespace Institute;
   class Institute{

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

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

【问题讨论】:

    标签: php namespaces type-hinting


    【解决方案1】:

    您仍然必须先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);
    

    【讨论】:

    • 如果我包含它们,那么使用命名空间有什么意义?你能澄清一下吗
    • 包括:将物理文件整合到一个逻辑脚本中。命名空间:逻辑上分离和排序的东西。我真的不知道如何在简短的评论中写出名称空间的用途(以及如何),我也不知道如何以多少方式编写名称空间和包含基本上没有共同点。事实是:你仍然必须包含文件,否则 PHP 无法处理文件中的内容。
    • 命名空间不是文件,它们主要用于组织类。更多信息:php.net/manual/en/language.namespaces.rationale.php
    • 您可以自动加载所有类:php.net/manual/en/language.oop5.autoload.php
    猜你喜欢
    • 2015-12-14
    • 2013-07-11
    • 2011-08-16
    • 2022-12-31
    • 2019-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-10
    相关资源
    最近更新 更多