Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a PHP class to separate files?

Tags:

php

class

I want to do something like class categories in Objective-C, to define a class in one file, implement some core methods there, then implement some helper methods in another without subclassing or interfaces, just "continue" the class.

Possible in PHP?

like image 686
Geri Borbás Avatar asked May 16 '13 20:05

Geri Borbás


1 Answers

As of PHP 5.4, you can accomplish this with Traits. To quote the official documentation:

Traits [enable] a developer to reuse sets of methods freely in several independent classes living in different class hierarchies. [...] A Trait is similar to a class, but only intended to group functionality in a fine-grained and consistent way. It is not possible to instantiate a Trait on its own. It is an addition to traditional inheritance and enables horizontal composition of behavior; that is, the application of class members without requiring inheritance.

Using a trait allows you to store helper methods that address cross-cutting concerns in a central place and use these methods in whatever classes you need.

// File "HelperMethodTrait.php" trait HelperMethodTrait {     public function myIncredibleUsefulHelperFunction()     {         return 42;     } }  // File "MyClass.php" class MyClass {     use HelperMethodTrait;      public function myDomainSpecificFunction()     {         return "foobar";     } }  $instance = new MyClass(); $instance->myIncredibleUsefulHelperFunction(); // 42 
like image 178
helmbert Avatar answered Oct 02 '22 04:10

helmbert