I have started writing a library of e-commerce classes in PHP as abstract classes with the intention of forcing the implementation of concrete classes to use a load() method which loads data into the objects:
abstract Cart {
abstract function load();
// other stuff ...
}
class MyCart extends Cart {
public function load()
{
// pull in data from anywhere ...
}
}
I was wondering if this is the right way to go about doing this...
I want to:
Keep the core library un-touched.
Keep it very simple, we intend to re-use this code and other people will be implementing it.
I've heard about adapters and things, although I haven't looked into these (yet).. can anyone point me in the right direction?
Cheers,
John.
Instead of using an abstract class, I would recommend using interfaces for this purpose:
interface Cart {
public function load();
// other stuff ...
}
class MyCart implements Cart {
public function load()
{
// pull in data from anywhere ...
}
}
Interfaces are used to describe the structure of a deriving class, it's the best way if you want to add different classes all offering the same methods. Another advantage would be that a class can only extend one parent class (i.e. your Cart class) but can implement several interfaces.
Read more about interfaces on PHP.net, here's one excerpt underlining why I think this pattern would fit your requirement:
Object interfaces allow you to create code which specifies which methods a class must implement, without having to define how these methods are handled.
Related
Sorry if this is a duplicate question or a common design principle, I have searched around but was unable to find any answers to this question. I'm probably just searching with the wrong keywords.
I have been looking at a popular library Sabre/Event (https://sabre.io/event/) and in the code there is a simple class/inheritance model that I am trying to understand:
The class EventEmitter implements EventEmitterInterface and uses EventEmitterTrait (see below for code).
There is a comment in EventEmitterTrait above the class which says:
* Using the trait + interface allows you to add EventEmitter capabilities
* without having to change your base-class.
I am trying to understand why this comment says this, and why it allows adding capabilities without changing the base class, and how that is different from just putting the routines into EventEmitter itself.
Couldn't you just extend EventEmitter and add capabilities in the derived class?
Simplified code:
// EventEmitter.php
class EventEmitter implements EventEmitterInterface {
use EventEmitterTrait;
}
// EventEmitterInterface.php
interface EventEmitterInterface {
// ... declares several function prototypes
}
// EventEmitterTrait.php
trait EventEmitterTrait {
// ... implements the routines declared in EventEmitterInterface
}
You're basically asking two questions here.
What are interfaces and why are they useful?
What are traits and why are they useful?
To understand why interfaces are useful you have to know a little about inheritance and OOP in general. If you've ever heard the term spaghetti code before (it's when you tend to write imperative code that's so tangled together you can hardly make sense of it) then you should liken that to the term lasagna code for OOP (that's when you extend a class to so many layers that it becomes difficult to understand which layer is doing what).
1. Interfaces
Interfaces diffuse some of this confusion by allow a class to implement a common set of methods without having to restrict the hierarchy of that class. we do not derive interfaces from a base class. We merely implement them into a given class.
A very clear and obvious example of that in PHP is DateTimeInterface. It provides a common set of methods which both DateTime and DateTimeImmutable will implement. It does not, however, tell those classes what the implementation is. A class is an implementation. An interface is just methods of a class sans implementation. However, since both things implement the same interface it's easy to test any class that implements that interface, since you know they will always have the same methods. So I know that both DateTime and DateTimeImmutable will implement the method format, which will accept a String as input and return a String, regardless of which class is implementing it. I could even write my own implementation of DateTime that implements DateTimeInterface and it is guaranteed to have that method with that same signature.
So imagine I wrote a method that accepts a DateTime object, and the method expects to run the format method on that object. If it doesn't care which class, specifically, is given to it, then that method could simply typehint its prototype as DateTimeInterface instead. Now anyone is free to implement DateTimeInterface in their own class, without having to extend from some base class, and provide my method with an object that's guaranteed to work the same way.
So in relation to your EventEmitter example, you can add the same capabilities of a class (like DateTime) to any class that might not even extend from DateTime, but as long as we know it implements the same interface, we know for sure it has the same methods with the same signatures. This would mean the same thing for EventEmitter.
2. Traits
Traits, unlike interfaces, actually can provide an implementation. They are also a form of horizontal inheritance, unlike the vertical inheritance of extending classes. Because two completely different class that do not derive from the same base class can use the same Trait. This is possible, because in PHP traits are basically just compiler-assisted copy and paste. Imagine, you literally copied the code inside of a trait and just pasted it into each class that uses it right before compile time. You'd get the same result. You're just injecting code into unrelated classes.
This is useful, because sometimes you have a method or set of methods that prove reusable in two distinct classes even though the rest of those classes have nothing else in common.
For example, imagine you are writing a CMS, where there is a Document class and a User class. Neither of these two classes are related in any meaningful way. They do very different things and it makes no sense for one of them to extend the other. However, they both share a particular behavior in common: flag() method that indicates the object has been flagged by a user for purposes of violating the Terms of Service.
trait FlagContent {
public function flag(Int $userId, String $reason): bool {
$this->flagged = true;
$this->byUserId = $userId;
$this->flagReason = $reason;
return $this->updateDatabase();
}
}
Now consider that perhaps your CMS has other content that's subject to being flagged, like a Image class, or a Video class, or even a Comment class. These classes are all typically unrelated. It probably wouldn't make much sense just to have a specific class for flagging content, especially if the properties of the relevant objects have to be passed around to this class to update the database, for example. It also doesn't make sense for them to derive from a base class (they're all completely unrelated to each other). It also doesn't make sense to rewrite this same code in every class, since it would easier to change it in one place instead of many.
So what seems to be most sensible here is to use a Trait.
So again, in relation to your EventEmitter example, they're giving you some traits you can reuse in your implementing class to basically make it easier to reuse the code without having to extend from a base class (horizontal inheritance).
Per Sabre's Event Emitter's docs on "Integration into other objects":
To add Emitter capabilities to any class, you can simply extend it.
If you cannot extend, because the class is already part of an existing
class hierarchy you can use the supplied trait.
So in this case, the idea is if you're using your own objects that already are part of a class hierarchy, you may simply implement the interface + use the trait, instead of extending the Emitter class (which you won't be able to).
The Integration into other objects documentation says:
If you cannot extend, because the class is already part of an existing class hierarchy you can use the supplied trait".
I understand it's a workaround when you already have an OOP design you don't want to alter and you want to add event capabilities. For example:
Model -> AppModel -> Customer
PHP doesn't have multiple inheritance so Customer can extend AppModel or Emitter but not both. If you implement the interface in Customer the code is not reusable elsewhere; if you implement in e.g. AppModel it's available everywhere, which might not be desirable.
With traits, you can write custom event code and cherry-pick where you reuse it.
This is an interesting question and I will try to give my take on it. As you asked,
What is the purpose of using traits to define functions for an interface ?
Traits basically gives you the ability to create some reusable code or functionality which can then be used any where in your code base. Now as it stands, PHP doesn't support multiple inheritance therefore traits and interfaces are there to solve that issue. The question here is why traits though ?? Well imagine a scenario like below,
class User
{
public function hasRatings()
{
// some how we want users to have ratings
}
public function hasBeenFavorited()
{
// other users can follow
}
public function name(){}
public function friends(){}
// and a few other methods
}
Now lets say that we have a post class which has the same logic as user and that can be achieved by having hasRatings() and hasBeenFavorited() methods. Now, one way would be to simply inherit from User Class.
class Post extends User
{
// Now we have access to the mentioned methods but we have inherited
// methods and properties which is not really needed here
}
Therefore, to solve this issue we can use traits.
trait UserActions
{
public function hasRatings()
{
// some how we want users to have ratings
}
public function hasBeenFavorited()
{
// other users can follow
}
}
Having that bit of logic we can now just use it any where in the code where ever it is required.
class User
{
use UserActions;
}
class Post
{
use UserActions;
}
Now lets say we have a report class where we want to generate certain report on the basis of user actions.
class Report
{
protected $user;
public function __construct(User $user)
{
$this->user = $user
}
public function generate()
{
return $this->user->hasRatings();
}
}
Now, what happens if i want to generate report for Post. The only way to achieve that would be to new up another report class i.e. maybe PostReport.. Can you see where I am getting at. Surely there could be another way, where i dont have to repeat myself. Thats where, interfaces or contracts come to place. Keeping that in mind, lets redefine our reports class and make it to accept a contract rather than concrete class which will always ensure that we have access to UserActions.
interface UserActionable
{
public function hasRatings();
public function hasBeenFavorited();
}
class Report
{
protected $actionable;
public function __construct(UserActionable $actionable)
{
$this->actionable = $actionable;
}
public function generate()
{
return $this->actionable->hasRatings();
}
}
//lets make our post and user implement the contract so we can pass them
// to report
class User implements UserActionable
{
uses UserActions;
}
class Post implements UserActionable
{
uses UserActions;
}
// Great now we can switch between user and post during run time to generate
// reports without changing the code base
$userReport = (new Report(new User))->generate();
$postReport = (new Report(new Post))->generate();
So in nutshell, interfaces and traits helps us to achieve design based on SOLID principles, much decoupled code and better composition. Hope that helps
An Abstract Class may and may not have abstract methods but an interface has unimplemented methods only. So what is the difference and advantage of using an interface if my abstract class has all of its methods marked as abstract?
Interfaces and Abstraction
The real power of use can be revealed in huge APIs with massive amount of classes that follow a well-thought flexible structure for future coding. Whether it may happen or not - you never know whether a code will be extended. Interfaces are merely used for semantic reasons. Imagine, you extend a deprecated version of an API and have the job to edit/alter/implement/update/improve/extend/modify the code to bring it up to date, whatever the reason is. You'd end up being frustrated if you did not think forward.
Small APIs can be made without the interfaces and that's where most people think interfaces were unnecessary. But then they lose their flexibility as soon as they become larger. They provide you a contract with classes which reminds you what is needed and to keep the overview. Interfaces must have public methods, if you have protected or private ones, just return them in a public method of a class with interface implemented..
Like you already explained, interfaces demand particular methods to be implemented, abstract classes don't demand it since you most likely extend them anyway. Methods can be re-defined and abstract methods MUST be defined in child classes. Methods mentioned in an interface only tells you that classes that have a contract with an interface must have these defined. It could be multiple interfaces, you don't inherit from them like you would do it with abstract classes.
Think like this way
The logic in it is to predict the future in what you are planning to build. Be it in architecture, infrastructure or mass production in factories. Just like the way you sort items like bookmarks, books, images in a folder. Because you know it would take longer to find a particular image if you didn't sort it. The semantic purpose of abstraction and interface is similar, especially in huge APIs.
An interface reperesents a frame of possibilities and requirements.
An abstraction preserves conceptual information that is relevant in a derived context.
I'll show you a typical structure for a start of an API with simplified contents wherein interfaces and abstract classes have a real point of usage for future extension.
/* Considering, this project will be widely expanded up to huge complexity.
This is a flexible base structure, for developers working in team. Imagine
there could be lots more variation of styles for certain purposes. */
// OOP STRUCT
// You might want to define multiple interfaces to separate the project
interface iString {
// These methods MUST be defined or else the developer receives an error
public function getContent();
public function description($desc);
}
/* Devs might want to add an additional method later on.
Traits are useful for quick use. (optional) */
trait desc {
private $desc;
public function description($desc) {
return $this->desc;
}
}
/* This is the base class for the content which requires a declaration
of methods being described in the interface */
class contents implements iString {
use desc; // use the method defined in a trait
private $str;
public function __construct($str) {
$this->str = $str;
}
public function getContent() {
return $this->str;
}
}
/* Or devs often consider abstract classes as the real base of the whole project/app.
Abstract classes allow the use of methods that can be modified/declared for further use in derived classes.
Interfaces can't do that */
abstract class stylize {
private $str;
// This typehint below makes sure that this value is assigned on interface
public function __construct(iString $str) {
$this->str = $str;
}
public function style() {
return $this->str->getContent();
}
abstract public function getContent();
}
// EXTENDED CLASSES
class bold extends stylize {
// Extended classes have to define abstract methods inherited from an abstract class. Non-abstract methods are not needed.
public function getContent() {
return "<strong>".parent::style()."</strong>";
}
}
class underline extends stylize {
public function getContent() {
return "<u>".parent::style()."</u>";
}
}
class upperCase extends stylize {
public function getContent() {
return strtoupper(parent::style());
}
}
// PROCEDUAL OUTPUT
// A tiny shortcut
$e = function($desc,$str) { echo $desc.": ".$str->getContent()."<br>"; };
// Content being used
$content = new contents('Hello World.');
$e("Normal",$content);
// Content being styled
$bold = new bold($content);
$underline = new underline($content);
$upper = new upperCase($content);
// Renders content with styles
$e("Bold",$bold);
$e("Underline",$underline);
$e("Uppercase",$upper);
Conclusion
Applying styles of text contents as an example is probably not appealing enough. But apart from this, it remains the same - if it does what it should do, then it's done. Like as if I would build an expandable eMail configuration API as a module for a CMS. This structure has a semantic process in proper coding.
Tipps
I'd suggest you to keep learning in small projects with this pattern, even if you think interfaces are not worth it. Keep doing this until you have it inside. My own personal advice for you:
If you think you have no idea where to start and what project to try it on, then try real world examples just follow this logic:
Vehicles (abstract class)
-> Ferrari (extended class)
-> Truck (extended class)
both have wheels (property)
both must be able to drive (method)
they perform a 1mile match race on a street (abstract method)
one is a slowpoke (extended property)
one is red one is blue (extended property)
and later a 3rd one comes and its a train (extended class)
who's going to win (some method)
Instantiate all vehicles and maintain privileges over interface and
abstraction.
...something like this...
Usually, classes containing huge bodies are supposed to be separated in single files + include these + define a namespace. Else wall of code would make you or someone else tired. Use Eclipse, best app for maintaining OOP.
Also, if it fits for your project, use phUML if you have Linux Ubuntu. It generates a graphical diagram for your current build if you have a lot of relating classes.
phUML is an API in PHP based on UML. It is an open-source project which generates any visual schemes for almost any popular programming language. I use it a lot, not just for PHP. Simply clone it at Github or download from dasunhegoda.com and follow installation guide there. This could interest you also: Typehinting on Interfaces
An Abstract Class allows for "partial implementation" (see the template method pattern), but in this case, if all methods are abstract, you don't see that benefit. One other thing you can do is include fields, you're not just limited to methods.
Remember, there's a conceptual difference between an "abstract method" and the contract defined by an interface. An abstract method has to be overridden by a subclass which is done through inheritence implementation. Any polymorphic calls (downcasting) will require one superclass per class or it would hit the diamond inheritance problem. This kind of inheritence based tree structure is typical of OO design.
As a contrast, an interface provides a signature of a contract to fulfil. You can fulfil many interface's needs as long as you retain the signature as there is no question of going back up the class hierarchy to find other implementations. Interfaces don't really rely on polymorphism to do this, it's based on a contract.
The other thing of note is you may have "protected" abstract methods, it makes no sense to do such a thing in an interface (in fact it's illegal to do so).
If an abstract class has all of its methods defined as abstract then you have to define its body in any subclasses and it displays similar behavior as interface.
Benefit :
Using interface instead of abstract class, you can implement more than one interfaces while using abstract class you can only extend one class at a time.
EDIT
Another difference I found about this is abstract class can have constructor while interface can't have.
REF: What is the use of constructor in abstract class in php
Can you help to clarify PHP Interface for me. I get that the main point is so that multiple classes can implement some of the same functions.
abstract class Plane {
public function openDoors();
}
interface Fliers {
public function fly();
}
now lets use them
class Boeing747 extends Plane implements Fliers {
public function fly() {
// some stuff
}
public function openDoors() {
// do something
}
}
and
class Tweety implements Fliers{
public function fly() {
// some stuff
}
}
In this case both Boeing747 and Tweety can implement the interface Fliers to access the public function fly(). However, in all examples that I am seeing, no functionality is actually defined in the interface, but rather when it is called inside of the class method itself.
Why would I not just define fly() as a separate function in each of Boeing747 and Tweety, instead of using the interface? Can you provide a concrete, basic example where it would be advantageous? Thanks!
It's a technique known as Design by Contract. Essentially, the interface serves as a contract, or a promise that any class that implements the interface will exhibit a particular set of behaviours. It allows your code to check capabilities of an object passed to it without having to worry about details that don't matter in the current context. For example, your openDoors() method could equally apply to a house, an aircraft, a canal lock, a car or anything else with doors, but other than having doors all of these things have very little in common. Even if they do all support the idea of having doors that can be opened, they may actually perform the door opening actions in wildly different ways.
The interface allows you to tell calling code that all these things have doors that you can open, without having to impose any artificial relationship between them when none exists. The instanceof keyword lets you check if an object meets certain criteria (if it's an instance of a particular class or subclass, or if it implements a particular interface).
interface ThingWithDoors {
public function openDoors ();
}
class House implements ThingWithDoors {
// Implement openDoors here
}
class CanalLock implements ThingWithDoors {
// Implement openDoors here
}
class Boeing747 extends Aircraft implements ThingWithDoors {
// Implement openDoors here
}
// Calling code
if ($object instanceof ThingWithDoors) {
// We don't know exactly what class we have, but we do know it has an openDoors method
$object -> openDoors ();
}
You could in theory achieve the same thing with other PHP functionality such as method_exists or Reflection, but those techniques are far from ideal because there's no contract to enforce anything (two different classes could implement door opening but have completely different names for the methods that do it, and you'd have to check for both with method_exists calls). Then, suppose, some other programmer adds a new class to the system that implements door opening in a completely different way from the ones you already check for. All the code where doors could be opened throughout the program would have to be updated to account for this new method too! If you add a new class to the system and it implements the ThingWithDoors interface, however, then all the code that opens doors will automatically work with the new class as it did with the old class without any modification at all (provided the new class implements the interface properly and respects return values that, sadly, aren't enforced by PHP interfaces).
Another nice thing about this for the programmer is that they don't have to keep looking up in the documentation/source code how to invoke certain behaviours in an object. If they know what the ThingWithDoors interface looks like then they know that everything that implements ThingWithDoors can have its doors opened, and that the method call for doing it is always going to be openDoors (). That can save you a fair bit of time as a developer, especially on a big project!
in OO PHP an object can have only one parent class. To see why this is adopted , lets use the Bird Class to show what multiple inheritance is and how it can lead to problems.
If you wanted to create a Wooping_Crane class, it would make sense to derive this class from Bird class. Suppose you also have an Endangered_Species class.
Multiple inheritance would allow you to create a Wooping_Crane class from combination of these two classes( Bird and Endangered classes). This would seem to be an excellent idea until you realize that both classes define an eating behaviour. Which one to prefer? so this is the disadvantage of multiple inheritance.
PHP solves this in two ways : Firstly , using interface - a class with function definition only.
If Endangered_Species were an interface rather than a class, having more than one eating function wouldn't matter. The method definition in the Bird class would act as the implementation of the interface function. In this way interfaces avoid the problem of defining the same function twice.
Secondly, using traits. ou can read about it in other posts.
I have an application in which a number of objects are all extending an abstract class which defines methods like create() edit() retrieve() and delete(). Since each of the child classes use the same logic for these functions, the abstract class defines that default behaviour, and in the few cases where it needs to be augmented, the child classes can override or use the hooks I've built in.
Now I'm having the situation where some of the child classes need to be made immutable, meaning that they shouldn't have edit() or delete() methods. This need sounds to me like a job for an interface named something like immutable which the immutable classes could implement. Problem is that interfaces don't stop methods from being called, they just enforce a method's existence. So this is obviously not going to work.
Making two parent classes, one for mutable objects and one for immutable ones is ugly and is probably asking for problems down the line which maintenance. I could have the immutable objects override the offending methods with an empty method that did nothing, but that also seems messy and like I'm not doing proper OOP at that point.
So what would you suggest as the best way to allow a large set of classes to all inherit a set of methods, but for some of them to not inherit all of the methods? (The application in question is written php, but general OOP techniques from any language can still be helpful).
create an immutable-base class as a child of the base class.
the immutable-base should implement final overrides of edit() and delete() which do nothing or throw an error.
Final, so that all immutable children are guaranteed not to be able to edit or delete
bonuses of this strategy
easily check if an object is immutable by testing for instanceof immutable-base
easily change objects from immutable and back again by modifing what it extends
Actually creating classes that have empty methods or throw errors is bad - such methods are confusing, they take up space and do nothing.
A better approach would be to make the immutable class the base class and make the mutable class extend it with adding methods for modification. This way each class has only those methods, that really belong there.
I like Java's approach to this. Throw an exception. Create an UnsupportedOperationException and for those implementations that shouldn't use a specific method throw one to let the user know they can't use this functionality for this implementation.
Another thought I wanted to throw out as a possible solution. Classes could implement an interface that looks like the following:
Interface Immutable {
const immutable = true;
}
and then the Base abstract class can write the delete() and edit() methods with
if (!$this->immutable) {
//do_stuff
}
This would also extend well to other classifications of class, like NonDeletable and NonEditable to allow for more fine grained behaviour.
Here is super short workaround, make your method final and start it with:
if(self::class!=static::class) return;#or throw an error
It will not prevent inheritance itself, but methods will not work in children classes (with error or without - is up to you).
As of PHP 5.4, you can use Traits.
For example, you could make a base class that only includes the methods that all child classes have:
class EntityManager {
public function create() {/*...*/}
public function retrieve() {/*...*/}
}
Then you could define a couple of traits:
trait EditTrait {
public function edit() {/*...*/}
}
trait DeleteTrait {
public function delete() {/*...*/}
}
You would then create an immutable child class like this:
class LogManager extends EntityManager {
...
}
And a mutable child class like this:
class ContactManager extends EntityManager {
use EditTrait;
use DeleteTrait;
...
}
Traits have some advantages over some of the other solutions here such as:
No duplication of code.
Single base class.
Methods that don't work or don't make sense, don't appear on classes that don't support them (especially important for docs and apis).
Lets say I have a parent class
class parent { }
.....
This parent has three sub class
class child1 { }
class child2 { }
class child3 { }
and these child classes have further smaller parts like
class child1subpar1 { }
class child1subpar2 {
public function foo() {
echo "hi";
}
}
class child2subpar1 { }
class child2subpar2 { }
Now, how to sum this whole up like
class child1 extends child1subpar1, child1subpar2 { }
class child2 extends child2subpar1, childsubpar1 { }
class parent extends child1,child2,child3 { }
I need to execute the methods in its inherited classes and do something like this
$objparent = new parent;
$objparent -> foo();
No, but multiple inheritance is generally considered a bad practice. You should favor composition instead, so you just use instances of classes you wanted to inherit inside your class.
And now when I look into your question again, it's not even an inheritance issue, you should use composition. Maybe if you provided more detail what you expect that class to do, we should answer more accurately.
UPDATE:
You will need to create one method for each of these classes' method which you would want to use - it's called Facade design pattern. Or maybe you are not aware that you can call methods of inner objects like this:
$parent->subObject->subSubObject->wantedMethod();
Facade pattern:
http://en.wikipedia.org/wiki/Facade_pattern
in your case facade wouldn't be anything else than creating one class and define every single method you want to use, and inside that method calling any method of any of your inner instances. But i really don't see any benefit coming from this instead of calling
instances and methods hierarchically
Seems like you're really confused about OOP.
Parent class has no awareness of its children. If you want to execute a child class, you need to create its instance.
Multiple inheritance is also not allowed in PHP (as well as many other popular languages like Java).
It might be worth looking at aggregation - passing smaller sub classes into child or event parent class. also, you can use implement multiple interfaces to force subclasses to have a set of required methods.
What you're doing is really backwards. Inheritance is used to bestow common, shared functionality upon objects without code duplication. The inheritance goes from Parent to Child, everything the Parent can do, the Child can do as well, but it may do more (it extends the functionality of the parent).
class Parent {
function everyoneCanDoThis() { }
}
class Child extends Parent {
// I can implicitly use the everyoneCanDoThis() function
function onlyChildrenCanDoThis() { }
}
Since this is a top-down structure, the Parent should not rely on any specific Child. The Parent does not execute or call functions of a Child. Only you call functions of a Child, but these functions may be inherited from a Parent class.
You should put everything you want every object to be able to do in a Parent class. Specific functionality that's only relevant to a specific object goes into a Child.
Multiple inheritance is a different can of worms that's not possible in PHP, for good reasons. Come back to composition, as suggested elsewhere here, when you get the basics of inheritance. :)
Composition just means that you take several objects and hold references to them in another object. It has nothing to do with inheritance, as each of these objects may or may not inherit from a Parent class and they're still individual objects.
class ComposedObject {
private $part1 = null;
private $part2 = null;
public function __constructor() {
$this->part1 = new Part1();
$this->part2 = new Part2();
}
public function doTask() {
return $this->part1->doSomeTask();
}
public function doOtherTask() {
return $this->part2->doSomeOtherTask();
}
}
The ComposedObject does not have any functionality itself, inherited or otherwise. But it holds two other objects that each carry some functionality. The functionality in the "parts" may be exposed directly, so they're called like $composedObject->part1->doSomeTask(), they may be encapsulated as in the example, so they're called like $composedObject->doTask() and are internally delegated, or you may use some __call() trickery to automatically delegate functions called on the composed object to one of its "parts". This has the same problem as multiple inheritance though; if two "parts" both contain a method of the same name, which one do you call?
+1 to the others. You really have it backwards. Children ALWAYS extends their parents.
But there is even something that can act kind of like multiple inheritance in PHP: The Decorator Pattern.
I wrote an article about it on my blog here.
A class can implement more than one interface, which is a slightly different thing.
When you inherit from a parent, you get everything it has unless you choose to override something, plus you can extend it by adding additional more specific stuff, but the parent should not know anything about the child.
When you implement an interface, the interface defines methods but it doesn't implement them. It is up to you to implement it. Different classes can implement the interface methods however they want as long as they follow what the interface says.
Inheritance tends to be overused and leads to bad programs. Perhaps if you told us what problem you're trying to solve, one of us could suggest how you can structure your classes.
Using Interface in Php maybe solve the question.