I am studying PHP and there is polymorphism example at the website i am studying at,
The Link for the Code:Pastebin, What i didn't understand is why Class b and Class c after those classes that have been extended with the function hellow when they are already contain this function, i know that this is how the polymorphism works, and i am not sure but i remember some one told me that 2 functions with same name can be in one class becouse each function has it own signature, but has i say i am not sure if can some one help me to understand it please i will be very thankful.
You are not talking about polymorphism here, but very simple inheritance. Multiple methods with the same name but different signatures are indeed possible in some OOP languages (like Java), but not PHP, where method names are unique in a class.
In your case, class b and c hello methods will simply replace (overload) the one already defined in a, which they extend.
But, from your b and c class, you may want to call a parent class method. That's exactly what a::hello($arg1, $arg2, date('Y-M-j')); does.
Related
I have one top class, let's say School.
And a couple of classes extending the School class.
Normally, if I had to call one of the child classes I would use:
new Math('aaa'), or new English(array('foo'));
Every child class has different parameters.
Now, what is better:
1) Creating factory method in the School class, so :
School::Factory('aaa') would return Math('aaa') class based on the given parameters to the Factory() method
2) Or simply calling each child classes directly?
EDIT: I have only two child classes, my problem is that I don't know if doing this is worth a bit of simplicity in production code. I would just check which parameters were passed to the Factory method, and based on this information I'd call one of these two classes. What do you think?
On one side I'll be able to write simpler code.
On the other every time I'll need to add new child class (though there are very little chances to do that), I'll need to change Factory() method either, so I have a dependency here.
1) Creating factory method in the School class, so :
You say that you have 2 classes extending School. Therefore, School should not act as a factory. The parent class shouldn't know anything about its children/subclasses.
2) Or simply calling each child classes directly?
Or you could have a "CourseFactory" or "LectureFactory" with createMath( aaa ), for example. Or depending on the case, maybe createLecture("math").
However, it makes no sense in your example that Math or English extend School (unless you mean MathSchool and EnglishSchool, but I understood it as MathCourse and EnglishCourse)
I have a confusion in why we use abstract classes or interfaces to implement or extend. interfaces doesn't contain any code so does the abstract methods. then why we use them. why don't we directly create methods and define them in our class rather we use interfaces or abstract classes. they don't contain any sort of code, we need to define them after extending them in our class. why we don't define these methods in our own class rather extend interfaces and then define them. I found such type of question asked several times in stackoverflow but couldn't understand the answer. can anyone please explain it in some simple way
The power of abstraction and interfaces comes from the fact that you can separate responsibilities and write modular code: One part of your (or someone else's) code may only care that you have an Animal and provide facilities to deal with Animals, without needing to know how they move or feed. A different part of your code may only care about defining lots of concrete animals, like Dogs, Birds, etc., with all the details of how they actually implement all their features.
By making the concrete classes (Dog, Bird, ...) extend a common, abstract interface (Animal), you can use a any now and future concrete class in a library written for the abstract interface -- you don't need to ask the library author to change the library to accommodate new Animals, and the library author doesn't need to know how features are concretely implemented.
For example, if you had two single algorithm, FeedBreakfast and FeedDinner, that would require a member function Animal::gobble(), then without inheritance you would need to implement each algorithm for each animal - i.e. you'd end up with M * N amount of code! By using a common, abstract interface you reduce this to M + N -- M algorithms and N concrete classes, and neither side needs to know of the other -- they just both need to know the interface.
Statically typed languages need to use this method to enable polymorphism. That is, you can write your code in terms of your abstract base class. Then you can "plug" in any subclass as an extension. This is called Liskov Substitution principle, or Open/Closed principle. Technically, this is called dynamic binding. That is, the method to call is selected during runtime depending on the subclass.
With dynamically typed languages the situation is completely different. I don't know if PHP is dynamically typed (I suspect it is), but in Ruby or Javascript, for example, you can program in terms of any object that conforms to a specific interface. That is, if your code expects an object that has a method called Print you can substitute with any other object that also has a Print method, without deriving from a common base class. The method will be looked up during runtime, that is why these languages are called "dynamic".
Hope this helps!
You use abstract classes or interfaces when you want to establish a protocol.
It sounds simple, but it's a very powerful concept. If you are forced to adhere to rules, then you cannot break them. If you cannot break the rules, you adhere to the protocol. Therefore, all the classes that implement your interface should inherently be compatible with each other. Naturally, there are exceptions among human kind who are able to break these rules by creating code that even interpreters cry when they have to parse it but that's a bit of an offtopic :)
For an interface, imagine you have a Class called "Message". This implements the Interface called SendMessage, which has a method definition of Send.
If you then create two subclasses of "Message". One could be "Email" and one could be "InstantMessage".
Now these both have the method Send(), which is defined in the SendMessage interface, and are blank. This now allows you to define differently what the Send() method does. However, because we know the classes Email, and InstantMessage use the interface SendMessage, we know that they both have the method Send();
So you could call Email.Send(), and InstantMessage.Send(), but do two different things. An interface defines methods available to several objects, but with the same method name.
Abstract classes/interfaces are mostly design time considerations. By defining methods as abstract and therefore the classes as abstract too.. we are ensuring that these methods will definitely be implemented by deriving classes. If they do not implement them they also become abstract.
Interfaces provides the luxury of distributing the must implement methods into different categories, so the required number of interfaces can be implemented.
the abstract classes guarantee that can't be instantiate, this is because are a generalization. for example,
in a game, exist a class player, but also exist classes defender and forward. the class player is the parent class of both classes. not is practice create a object player, because a team need a especific player.
The interfaces are related with polymorphism. every class, use methods according to its behavior.
i hope this help you
The idea behind an abstract class is that you can define some common functionality of a set of similar classes, but leave other details up to the implementing (extending) classes. In a way they are similar to interfaces, except that you can actually implement some of the functions in the abstract class.
But what's the point, I hear you ask? Well, you only have to write the common code once, although you can do this in a concrete (non-abstract) base class too. But also you may not want other programmers to instantiate the base class, so this is where the real power of abstract classes come in.
Let me show an example to help illustrate my point. Imagine you are writing a program to classify all of the animals in a zoo. Animals can be classified into certain types, bird, reptile, mammal, insect, arachnid, fish, etc, and then down to their species such as dog, cat, parrot or kangaroo. The base class, Animal, can provide some of the common functionality to all of these. It might have a function called eat() which all animals do in a similar way and so the function is written out to describe the process of an animal eating. It might contain another function, walk(), but this one is abstract, since different animals will implement this in a different way. All subclasses of the Animal class will need to implement this method.
The major bonus of this is that somewhere in your code you can call a function that takes an Animal as a parameter. You know that you can call the eat() and walk() functions on this parameter because all Animals can eat and walk. This is called polymorphism and is an important trait of Object Oriented Programming.
I hope this has helped you. Please feel free to discuss or ask further questions if you still can't see the value of abstract classes.
I have been trying to learn OOP using PHP5 and I am having trouble wrapping my head around a couple of things.
First; I am understanding Inheritance in OOP, but what I am not understanding in PHP is why I can only use extends once to extend a parent class. I have been doing some reading online and a few times I have seen where it is not good practice to use extends more than once, that's why it's not available, is this true?
Second; Abstract vs. Interface, I read a way to Inherit one class many times is to use Interface and or Abstract. Is this correct?
Third; I am writing a very simple class using Inheritance and I am having a problem understanding how to properly contruct it. I have looked thru php.net and OS and have seen many classes and how they are written, but could anyone take the time to write a simple example in PHP using .... let's say a mammal class as the parent class and have dog, cat, and bear and the child classes.
I know I could find something online that has already been written, but this way I can converse with the person who wrote the class.
First; I am understanding Inheritance in OOP, but what I am not understanding in PHP is why I can only use extends once to extend a parent class. I have been doing some reading online and a few times I have seen where it is not good practice to use extends more than once, that's why it's not available, is this true?
In short: Its just a design decission from the PHP core developers. Multiple inheritance brings up many questions, for example what should happen, when two parent classes implements the same method? To avoid such conflicts some languages decide to not support it (e.g. Java too ;)). There is no real downside in it.
Second; Abstract vs. Interface, I read a way to Inherit one class many times is to use Interface and or Abstract. Is this correct?
You can extend every class as much as you like. There is no limitation neither for classes, abstract classes, nor interfaces. However, its possible to implement (implements keyword) more than one interface into one class.
Third; I am writing a very simple class using Inheritance and I am having a problem understanding how to properly contruct it. I have looked thru php.net and OS and have seen many classes and how they are written, but could anyone take the time to write a simple example in PHP using .... let's say a mammal class as the parent class and have dog, cat, and bear and the child classes.
abstract class Mammal {}
class Dog extends Mammal {}
class Cat extends Mammal {}
class Bear extends Mammal {}
Yes it's true PHP only officialy supports extending one class at a time, its a bug bear to all OOP because there's no good OOP reason not to be able to but there is for the language. It's also true you can circumvent it, not recommended however because it's not supported by the language for a reason (I forget now).
Not sure what you mean by versus, Abstract classes are classes that should be abstracted before using them. Think of them as 80% complete classes, there are a few functions missing for it to work which must be implemented on a per application level.
Interfaces are the kind of bones of a class, there's no functionality there but all functions are defined. They aren't to be extended or used they are to be referenced against.If a class implements and interface it commits to implement all the function stated in the interfaces (and possibly more) and PHP throws an error if that's not the case.
A very simple example
class Mammal{
function getBones(){}
}
class Dog extends Mammal{
function bark(){}
}
class Cat extends Mammal{
function meow(){}
}
$d = new Dog()
$d->bark()
//Works
$d->getBones()
//works
$d->meow()
//does not work, is a cat function
I think you are talking about Multiple Inheritance? Technically, it's a design decision of the PHP developers. There are other languages which allow it.
Multiple inheritance has some technical problems (Diamond Problem), but there is a good theoretical argument against it: A class should have one responsibility (Single Responsibility Principle, it talks of "object" because there are classless yet object-oriented languages). Two different classes usually have different responsibilities, so if a class inherits from both of them, it would have two responsibilities, violating the SRP.
See Search for "abstract class interface" – use interface to define the methods a class must implement to satisfy a contract, use abstract class if you want to partially implement something (usually an interface).
Impossible, because you did not say which aspects of the mammals should be modeled. Without knowing that, it would even be impossible to know if different mammal classes or a common base class are needed.
I have a large class that I'm breaking up into smaller chunks.
So I have a base class and a new class which extends the base class.
My problem is, Can I call the extended class from the base class? This just doesn't seem right.
// a.php
class A {
// set all the properties and runs some validation and functionality in the process
}
// b.php
class B extends A {
// needs all the same validation as class A and adds more functionality
}
To start the process I can only call class A, Example:
$process = new A();
in the class A I need to decide if class B functionality is needed
class A {
if($condition) {
include_once('b.php');
$new_process = new B();
$new_process->doMoreStuff();
}
}
I could add the doMoreStuff() (well a ton more functionality) but this defeats the purpose of having the smaller class file sizes.
I know the right way would be to create a wrapper script and put the logic in there, if to use class A or B. But is there any other reason why I couldn't do as I've requested?
UPDATE:
So let me clarify what class A is:
Class A sets up all the database connections, validation of the INI properties, and sets the initial logging values. Class A also has a workflow/process for handling a specific request.
Class B needs class A's database, INI properties and logging but also offers a new workflow/process. I just wanted to extend the functionality of A into another class (as to make it more manageable).
So I'm thinking there should be a decision class C that decides to use Class A only or Class B which extends Class A.
Just wanted to confirm that this would be the best bet, thanks for the input
sounds like maybe you should be using a factory pattern, although hard to tell without more info. some sort of oop pattern is applicable here though. check this out.
http://www.php.net/manual/en/language.oop5.patterns.php
EDIT
Your idea is a step in the right direction, but it seems your application violates the single responsibility principle (SRP). Class A has several responsibilities, and therfore many reasons that it may change. You may want to instead have one class that initializes, one class that handles the DB connection, and one class that handles logging. This will make your application much easier to modify in the future. You would then pass these classes into whatever other classes need them using dependency injection (basically through construct or method arguments), or simply use them in the wrapper class when needed.
If class B only shows up as part of class A then you should make it at least obvious that it cannot be used outside of the class. Set some variable or something before you include b.php and error out if it's not set inside of b, so that if somebody else includes it, the variable will not be set, and it will be obvious that the class is not meant to be used outside of class A.
And is B really a subclass of A if you're creating a separate instance of it? your new object initialized as an A will act like a B during construction, but if some method requires a B object, you can't pass in the object you initialized as an A, whereas if you used a wrapper class, and it actually returned a B, it would work correctly for places that expect a B. It depends on how complex your situation is, if this may come up or not.
factory pattern is definitely one way to go here, but another thing to keep in mind is the difference between "is a" and "has a".
the way that you have everything working right now, using inheritance, is an "is a" kind of relationship b is an a.
the has a relationship woould make b its own class, with a property of the type of a. that way you could initialize b with an a class object, and make use of all data and validation in a, without the two classes having any inheritance based relationship.
not the best explanation of the differences... the important question though is whether or not those properties/methods from a actually belong as properties or methods on b.
I've faced a situation when I want to extend two parent classes, but php does not allow this.
Why I can't extend more than one class, but can implement more than one interface. What's wrong with extending many classes?
It seemed to me like a pretty obvious thing, until I got parse errors.
Is it a bad practice? If so, what are the alternatives?
Is it possible in other languages?
Why multiple inheritance is forbidden in some/most programming languages is argued with the diamond problem http://en.wikipedia.org/wiki/Diamond_problem.
Put simple if you have a car that can swim and drive because it inherits from vehicle and boat what happens on execution of the move function!?
Try using interfaces and follow the Strategy pattern or State pattern.
You're probably looking for: Multiple Inheritance in PHP.
It seems to be possible in Python.
Take a look at Can I extend a class using more than 1 class in PHP?
Is it a bad practice? If so, what are alternatives?
Unless the language is specifically designed for it, yes. Consider, you have two classes, A and B. Both classes provide a public method foo() which have identical signatures (not hard in PHP). Now, you make a class C which extends both A and B.
Now, you call C.foo(). Without explicit instructions, how does the interpreter know which version of foo() to call?
It's not supported by PHP. It can however be simulated using runkit, APD or by just overriding __call and __get to simulate inheritance from multiple classes. Symfony (and I seldomly recommand that) also provides "sfMixin" or "sfMixer" for multiple inheritance.
Separate classes implementing the same method is not a good argument against multiple inheritance, as currently multiple interfaces can be implemented. You just can't implement two interfaces with the same method. Quote from http://www.php.net/manual/en/language.oop5.interfaces.php: "A class cannot implement two interfaces that share function names, since it would cause ambiguity."
I know this question is 2 years old but I've only just had the same problem. My work-around is this: if you have one regular class and two abstracts and want to extend both, e.g abstract class AbstractOne and abstract class AbstractTwo, you can say:
abstract class AbstractOne extends AbstractTwo {
}
Then add to the main class like this:
class MyMainClass extends AbstractOne {
}
This way, it inherits both AbstractOne and AbstractTwo.