Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between extending a class and including it in PHP?

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?

like image 994
daniel Avatar asked Jun 09 '09 15:06

daniel


2 Answers

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).

like image 163
chaos Avatar answered Sep 18 '22 12:09

chaos


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

like image 41
Allain Lalonde Avatar answered Sep 21 '22 12:09

Allain Lalonde