views:

255

answers:

3

Can someone explain to me what the difference between

include_once 'classb.php'
class A
{
     $a = new B
}

and

class A extends B
{
     $a = new B
}

is?

What advantages/disadvantages are there to extending a class vs. including the .php file?

+7  A: 

Your include_once reads in a source file, which in this case presumably has a class definition for B in it. Your extends sets up class A as inheriting class B, i.e. A gets everything in B and can then define its own modifications to that basic structure. There isn't really any relationship at all between the two operations, and your $a = new B operations are nonsensical (not to mention syntax errors).

chaos
+3  A: 

In case you're looking for a higher level answer...

Using extends binds A to doing things similarly to B, whereas creating an instance of B within A doesn't impose any restrictions on A.

The second approach is called Composition and is generally the preferred approach to building OO systems since it doesn't yield tall Class hierarchies and is more flexible long term. It does however yield slightly slower code, and more of it than then simple use of extends.

My 2 Cents

Allain Lalonde
what is slower? extending or including? i just did a small benchmark, and i found that extending makes the code slightly slower. is this what you meant?
daniel
Say I want to invoke foo on A and it delegates foo to B, then there'll be time taken for two method calls in the Composition approach. If A extends B then invoking foo on A is considered 1 method call and there's no need for a lookup except when the classes are defined (which happens once).
Allain Lalonde
A: 

First of all, include is a command that read a php source file and treats it as it was written in place of the include directive. You can use it on any php source file and is not related to the class inheritance.

By the way, if you don't include the file containing the class A source code you can't extends that class.

Extendind a class with the keyword extends imply the concept of inheritance that is a key concept in object oriented programming.

You get a class (A) with some methods and need a similar class (B) with a slight different behaviour, you can derive the new class extendig the class A and modifying just the methods that have to change (it is called overriding) or adding new ones.

In opposite to the inheritance there is the composition. With the composition you don't extends a class to change its behavoiur instead you have to do a patchwork of classes in order to obtain the desired behaviour.

On wikipedia you can find a better explanation on object composition and class inheritance

It seems there is a little confusione on these concepts, as you extend your class A and, at the same time, you try to compose it (by the way, the correct syntax is $a=new B();).

A useful reference it, obviously, Gof, Design patterns

Eineki