Why can't I split a class into multiple files

I am trying to create a TestClass class divided into several files. I divided it into 3 files, where the first TestClassPart1.php file has the beginning of the class class TestClass { , and the last TestClassPart3.php file has the class closing bracket. These are 3 files

 //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"; } } 

Then I recombine in the actual class file called TestClass.php , so TestClass.php is just the glue of all three files.

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

I thought this should work, but when I try to instantiate TestClass and call one of the functions, I get parse error, expecting T_FUNCTION' in C:\wamp\www\TestClassPart1.php on line 5 . Line 5 is } of func1()

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

Doesn't that work? I thought you could distribute the class across multiple files without a problem. Am I doing it wrong?

+4
source share
3 answers

When you require file, PHP will analyze and evaluate the content.

Your class is incomplete, so when PHP parses

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

he cannot understand the class because there is no closing}.

Plain.


And anticipate the next question. it

 class Foo { include 'methods.php' } 

will not work either.


From the PHP Manual for OOP 4 (could not find it in 5)

You cannot split a class definition into multiple files. You can also NOT break a class definition into multiple PHP blocks if the gap is not in the method declaration. The following actions will not be performed:

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

However, the following is allowed:

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

If you are looking for “Horizontal reuse”, either wait for PHP.next to appear, which will include “Features” , or take a look

+8
source

I had the same thought as a purely academic interest. It is not possible to directly execute what you ask, although you can use PHP to create PHP, which is then evaluated by the server.

Shortly speaking:

Do not worry

Short story:

  • it adds a level of insecurity to your classification system as it becomes more difficult to control access to files.
  • it slows down compilation / caching of pages
  • you really don't need to force the square snap into the round hole.

Instead, use the right OOP methods to classify functionality and extend existing classes.

+2
source

If you must do this this way, you can use include_once() to directly drag the file into your script.

0
source

Source: https://habr.com/ru/post/1334398/


All Articles