gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:04:03 26 4
gpt4 key购买 nike

我正在尝试创建一个分为多个文件的类 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com