【问题标题】:Why I can't divide a class over several files为什么我不能将一个类划分为多个文件
【发布时间】:2011-01-05 17:30:37
【问题描述】:

我正在尝试创建一个分为多个文件的类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.phpso 的实际类文件中重新组合,所以 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 on line 5。第 5 行是 func1()}

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

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

【问题讨论】:

  • 您为什么要这样做?如果类太大以至于无法在单个文件中进行管理,那么重构或分解成更小的类可能已经成熟了。
  • 用 todo 标记类(如果您使用 phpdoc 或等效项)然后在有时间/机会时返回它不是“快速解决方案”吗?即:保持原样,而不是提供解决问题的假象。

标签: php oop class


【解决方案1】:

当您require 一个文件时,PHP 将解析并评估其内容。

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

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

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

就这么简单。


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

class Foo
{
    include 'methods.php'
}

也不行。


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

您不能将一个类定义分解为多个文件。您也不能将一个类定义分解为多个 PHP 块,除非中断位于方法声明中。以下将不起作用:

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

但是,以下是允许的:

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

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

【讨论】:

    【解决方案2】:

    前段时间,出于纯粹的学术兴趣,我也有同样的想法。虽然您可以使用 PHP 生成 PHP,然后由服务器进行评估,但不能直接执行您的要求。

    长话短说:

    别打扰

    长话短说:

    • 它为您的分类系统增加了一定程度的不安全性,因为控制文件访问变得更加困难。
    • 它会减慢页面的编译/缓存速度
    • 您真的不需要将方形钉子强行插入圆孔中。

    改为:使用适当的 OOP 实践,将功能分离到类中并扩展现有类。

    【讨论】:

      【解决方案3】:

      如果您必须这样做,您可以使用include_once() 直接将文件推送到您的脚本中。

      【讨论】:

      • 不完全。 PHP 必须格式正确才能执行。在这种情况下,php 将无效,因为右括号将丢失。
      • 我在想那些只是打印错误的代码行。这些文件实际上是这样构造的吗?哎哟。我只是重新考虑我的编码方式,因为我认为这样做没有用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-03
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多