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 } 

this is?

What are the advantages / disadvantages for extending a class compared to a .php file?

+6
oop include php extends
source share
4 answers

Your include_once reads in the source file, which in this case supposedly has a class definition for B in it. Your extends sets class A as it inherits class B , i.e. A gets everything in B and can then determine its own changes in this basic structure. There is no connection at all between these two operations, and your $a = new B operations are pointless (not to mention syntax errors).

+8
source share

If you are looking for a higher level answer ...

Using extensions binds A to do things similar to B, while instantiating B inside A does not impose any restrictions on A.

The second approach is called composition and, as a rule, is the preferred approach to creating OO systems, since it does not provide high class hierarchies and is more flexible in the long run. However, it gives a bit slower code, and more than just using extensions.

My 2 cents

+6
source share

second, i.e. extension is a class operation. Firstly, i.e. include is a file operation (before compilation).

So - the second is impossible. without the first.

+2
source share

First of all, include is a command that reads the php source file and processes it, since it was written instead of the include directive. You can use it in any php source file and are not related to class inheritance.

By the way, if you do not include the file containing the class A source code, you cannot extend this class.

Extending a class with the extends keyword implies the concept of inheritance, which is a key concept in object-oriented programming.

You get a class (A) with some methods and need a similar class (B) with a little different behavior, you can get a new extig class of class A and modify only the methods that need to be changed (it is called redefinition) or adding new ones.

In contrast to inheritance, there is composition. With composition, you do not extend the class to change its behavior; instead, you need to patch classes to get the desired behavior.

In wikipedia you can find a more detailed explanation of the composition of the object and [class inheritance] ( http://en.wikipedia.org/wiki/Inheritance_(computer_science))

There seems to be some confusion in these concepts as you extend your class A and at the same time try to compose it (by the way, the correct syntax is $ a = new B () ;. )

Useful link, obviously [Gof, Design patterns] ( http://en.wikipedia.org/wiki/Design_Patterns_(book))

+1
source share

All Articles