php - 为什么我不能将一个类划分为多个文件

标签 php oop class

我正在尝试创建一个分为多个文件的类 TestClass。我将其拆分为 3 个文件,其中第一个文件 TestClassPart1.php 具有类 class TestClass { 的开头,最后一个文件 TestClassPart3.php 有类的右括号。这是 3 个文件

//TestClassPart1.php
<?php  
class TestClass {    
   public function func1(){ 
      echo "func 1"; 
   }

//TestClassPart2.php
<?php    
   public function func2(){ echo "func 2"; }

//TestClassPart3.php
<?php    
   public function func3(){ echo "func 3"; }

}

然后我在名为 TestClass.php 的实际类文件中重新组合,因此 TestClass.php 只是所有 3 个文件的粘合剂。

<?php
require 'TestClassPart1.php';
require 'TestClassPart2.php';
require 'TestClassPart3.php';

我认为这应该可行,但是当我尝试创建 TestClass 实例并调用其中一个函数时,我收到 parse error, expecting T_FUNCTION' in C:\wamp\www\TestClassPart1.php 第 5 行。第5行是func1()

<?php
require 'TestClass.php';
$nc = new TestClass();
$nc->func1();

这不应该工作吗?我认为您可以将一个类分布在多个文件上,没问题。我做错了吗?

最佳答案

当您需要一个文件时,PHP 将解析和计算内容。

你的类不完整,所以PHP解析的时候

class TestClass {    
   public function func1(){ 
      echo "func 1"; 
   }

它无法理解该类,因为缺少结束符 }。

就这么简单。


并预测您的下一个问题。这个

class Foo
{
    include 'methods.php'
}

也不行。


来自PHP Manual on OOP 4 (在 5 内找不到)

You can NOT break up a class definition into multiple files. You also can NOT break a class definition into multiple PHP blocks, unless the break is within a method declaration. The following will not work:

<?php
class test {
?>
<?php
    function test() {
        print 'OK';
    }
}
?>

However, the following is allowed:

<?php
class test {
    function test() {
        ?>
        <?php
        print 'OK';
    }
}
?>

如果您正在寻找 Horizontal Reuse, either wait for PHP.next, which will include Traits或者看看

关于php - 为什么我不能将一个类划分为多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4607181/

相关文章:

javascript - 我想在表中显示以下数据

php - 在 PHP 中获取服务器时区

java - 给定相同类型的对象更新当前对象

Linq 因 Range 变量 'Username' 隐藏变量而出错

c++ - 堆与堆栈内存使用 C++ 用于动态创建的类

c++ - 比较单个 vector 中的值

javascript - PHP - 用户链接

php - 基于单选按钮状态的链接点击动态 href 生成 : PHP interaction with javascript

java - 如何获取我在另一个对象中创建的变量

javascript - 扩展 Aloha Editor 的格式插件