 |
Account Login
|
 |
 |
Latest Articles
|
 |
 |
IRC Channel
|
 |
 |
Associates
|
 |
 |
Associates
|
 |
|
 |
 |
|
 |
11-26-2007, 07:30 PM
|
#1 (permalink)
|
|
The Prestige
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
|
Abstract Classes
Hello all,
This is the second tutorial I have written for the wonderful community of TalkPHP :), the first one was about the singleton/factory pattern, within that article i briefly touched upon the idea of using interfaces, then Karl followed up with a great article explaining them further ( Working with Interfaces).
In this short little tutorial I am going to be covering abstract classes within PHP5
(as i understand them, Ive never really been a big fan of OO theory, so if i get something wrong then please do correct me).
As you may recall interfaces do not and cannot define the operational behavior of an object, becasue interfaces are 100% abstracted, but rather they define how you (the developer) is to work with the class.
The way i visualize this is to think that i am entering into an 'agreement' between me and PHP, in other words I have defined a list of methods (rules) in the interface that I (or any other developer) must implement in any implemented class, so in any implemented classes i am agreeing to conform with the interface's rules. get me?
Abstract classes are a bit different, an abstract class is a partially abstracted class and can contain functioning methods and also abstracted methods that any class that inherits from it must implement.
confused? don't be, an abstract class merely exists to be extended (inherited) and contains methods and variables common to all derived sub-classes and therefore cannot be directly instantiated.
Now hopefully I've explained the differences, if not, this maybe useful to you, with an interface the creator is saying "Implemented class must implement X, Y, Z as defined in the Interface" where as an abstract he could say "extended class of abstract inherits X but must implement Y, Z as defined in abstract"
Right with the boring stuff out of the way, heres an example i will use from my last article, a DB class but in this case i want to have a common method for all of my objects that inherit the abstract, in this case its an error logging method (I haven't bothered making it a working example, but you should be able to alter to your needs):
PHP Code:
abstract class DB_Abstract { //Noraml method, this get inherited by child objects (aslong as its public or protected) public function logError() { echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } //Abstract methods, the inherited object must implement these much like an implemented class from an interface abstract public function connect(); abstract public function escape_string(); abstract public function insert(); abstract public function select(); abstract public function delete(); abstract public function update(); abstract public function close(); }
class DB_mysql extends DB_Abstract //we are inheriting DB_Abstract { //We must implement all methods defined as abstract in the parent class public function connect(){ echo 'From: <b>' . __CLASS__ . '::' .__FUNCTION__ . '()</b><br />'; } public function escape_string() { echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } public function insert(){ echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } public function select(){ echo 'From: <b>' . __CLASS__ . '::' .__FUNCTION__ . '()</b><br />'; } public function delete(){ echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } public function update(){ echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } public function close(){ echo 'From: <b>' . __CLASS__ . '::' . __FUNCTION__ . '()</b><br />'; } }
Right, the first class has the keyword 'abstract' attached to the front of the class definition, which tells PHP that this class is abstract.
Im not going to explain most of the class because I have commented it and since this is an advanced tutorial you should be able to decipher it xD.
Anyway if we try to instantiate DB_Abstract,
PHP Code:
$mysql = new DB_Abstract();
PHP will produce :
HTML Code:
Fatal error: Cannot instantiate abstract class DB_Abstract
This is because you cant instantiate abstracts because they are like interfaces, abstracted types
So we must instantiate the derived object (should have been obvious but just incase anyone didnt see it)
PHP Code:
$mysql = new DB_mysql();
Now to illustrate this we can call:
PHP Code:
$mysql->connect();//from the DB_mysql class, that implements the abstract method in DB_Abstract $mysql->logError();//from the method implemented in DB_Abstract
Because we have inherited, or in php 'extended' from the abstract, we have access to DB_Abstract::logError() from DB_mysql, but in the abstract we defined connect() as abstract so PHP will want an implementation of it within the inherited object, which in this case we do, but if i was to comment out connect() in DB_mysql, PHP will produce:
HTML Code:
Fatal error: Class DB_mysql contains 1 abstract method and must therefore be declared abstract or implement the remaining methods.
So in short, abstracts are much like interfaces, but they allow you to have common methods inherited into derived objects, where as interfaces just enforce the API of the object.
I hope that made it clear, like i said, I've never been a guy that likes Object Oriented Theory, in fact it bores me to suicide sometimes so if there is something erroneous here then don't hesitate to shout at me :)
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
Last edited by sketchMedia : 11-27-2007 at 06:35 AM.
Reason: somehow managed to spell 'inherited' horrendously wrong
|
|
|
|
|
The Following User Says Thank You to sketchMedia For This Useful Post:
|
|
11-27-2007, 04:14 PM
|
#2 (permalink)
|
|
The Reckoner
Join Date: Sep 2007
Posts: 437
Thanks: 22
|
Nice article sketch, good follow up to our previous articles.
__________________
Any fool can write code that a computer can understand. Good programmers write code that humans can understand.
|
|
|
|
11-27-2007, 04:21 PM
|
#3 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
As I understand it, all abstract functions also default to public, and although it is definitely good practice to put in the public, it's not a requirement to make the abstract class work well. The most perplexing part of abstracts, and interfaces while we're at it, were that they didn't really add anything to make my code work. After all, I could omit the abstract class, and my other classes that once inherited the abstract class, would still work perfectly fine.
However, and here is the really big however, since I've started to code with abiding by standards, you will realise that entering into an agreement with PHP is a big must, especially if it's not only you who's going to be editing the code. For instance, in programming there are million and one various ways to do the same task. There's a good chance that if you let someone loose on your code with a task in mind, they'd implement it in a only totally different way to which you have. Thus, when you enter into an agreement with PHP, everybody else who comes along must also enter into that agreement with PHP - there's no two ways about it! So if I am creating my child classes which hand out drinks to my PHP code (lucky PHP code!) then I can tell everybody who works on my code, to implement the giveDrink function, like so:
php Code:
abstract public function giveDrink($szDrink);
That way there are no arguments as to how something should be implemented, you've defined the rounds and everybody must abide by that, otherwise you get anarchy, and as I'm sure you're well aware, pure chaos isn't too far behind.
Essentially, you define the rules and everybody must stick to those rules. Great article, Sketch! I just felt it was necessary to cover the reasons why you would use it, I'm sure many are looking over this and thinking, pfft, I don't need that! Well, you will soon :) If you stick with your programming, I can assure you!
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
|
|
|
11-27-2007, 05:33 PM
|
#4 (permalink)
|
|
The Prestige
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
|
Thats a good summary, yes i agree these features are pretty perplexing especially when your trying to learn them, because as you rightly say, they don't really do much apart from create rules and people may take the attitude 'Why the hell do i need that, i can get the same results with normal inheritance' i know i did, BUT when you actually start using them you see the power that they provide especially when there is more than one coder at work with the code.
I'm glad you like it.
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
|
|
|
|
11-28-2007, 02:05 PM
|
#5 (permalink)
|
|
The Acquainted
Join Date: Nov 2007
Posts: 127
Thanks: 14
|
Good article, keep em' coming. :)
Although, abstract classes and/or interfaces can't exactly force developers to ignore extending/implementing them.
|
|
|
|
11-28-2007, 02:39 PM
|
#6 (permalink)
|
|
La Vida es Sueño
Join Date: Sep 2007
Location: Oldham
Posts: 2,280
Thanks: 90
|
You're right there. A developer must implement and/or extend depending on whether it's an abstract or an interface. And that's possibly somewhat of a downfall. Although I can't seem to think of any other way around that, you'll just have to capitalise, underline and embolden the fact that ALL CHILD CLASSES MUST EXTEND THE LOVELY ABSTRACT.
__________________
The man who comes back through the Door in the Wall will never be quite the same as the man who went out.
|
|
|
11-28-2007, 06:39 PM
|
#7 (permalink)
|
|
The Contributor
Join Date: Nov 2007
Location: California
Posts: 82
Thanks: 0
|
while we're on the topic of "forcing" someone to extend off of a class or what not.
There are ways to use PHP to restrict access to other parts of your core classes, by using the PHP function: is_subclass_of() ( you can grab a whole bunch of other class/object functions at http://www.php.net/manual/en/ref.classobj.php )
By using little tricks like this, you can enforce parent to child relationships. Also, consider the following, which are possible thanks to Abstract classes, as these are possible ways to also enforce parent to child relationships...
a. To Start, if you don't trust other developers to follow the rules, put all other developers are only allowed to edit files within a certain branch. This can be done with a version control client, or simply, giving them an FTP login that restricts them to a certain folder subset.
b. Keeping your core files out of their branches forces them to include them, and "interface" through them.
c. Keeping your methods private/protected, means you can restrict the developers ability to override your precautions already set in place.
d. Then, have 'sanity checks' to make sure access to the database and/or other core classes / modules is restricted to children / parent classes. (if you so choose)
But yes, extending or implementing, totally optional.
But you can gain a whole lot by extending or implementing abstract classes or interfaces.
A lot of PHP4 users don't really see this right off of the bat, thinking that this is one of those things for languages like Java or C++, classes with visibility restrictions etc etc, bleh. Those languages are very different than PHP, which is such a weakly typed language.
And I'll be honest, not everything you do needs an abstract class, or an interface. Experience will tell one day, "Hey, this would be a great place to plop down an interface." or "Damn, I should stick these methods in abstract classes."
I personally, love the flexibility you have with these features in PHP5.
So yeah, in my rambling I think I came to a point.
|
|
|
|
11-28-2007, 07:36 PM
|
#8 (permalink)
|
|
The Prestige
Join Date: Oct 2007
Location: Manchester, UK
Posts: 854
Thanks: 32
|
thanks dschreck, some good points there, like the idea of forcing a parent - child relationship.
You cant force the developer to implement the interface, whereas if an abstract is used, if for example there is a method in the abstract that the devloper needs to inherit, then he will have to extend the abstract, therefore he will inherit the rules thats why i prefer abstracts to interfaces (not just because of that).
__________________
mysql> SELECT * FROM `users` WHERE `users`.`clue` > 0;
Empty set (0.00 sec)
|
|
|
|
10-18-2012, 02:42 PM
|
#9 (permalink)
|
|
The Addict
Join Date: Oct 2012
Posts: 244
Thanks: 0
|
Some conservatives have Coach Factory Outlet pushed that critique further, saying that Mr. Obama’s policies are too costly, often assist the wrong people Louis Vuitton Belts and could have the paradoxical effect of driving up college costs. The dispute turns not just on different Coach Factory Outlet assessments of how policies play out, but on differing philosophical views about the role of government. During Gucci Belts his time in office, Mr. Obama has sharply increased aid to low- and middle-income students, notably through the Pell Grant Coach Factory Outlet program, which grew from $14.6 billion given to 6 million students in 2008, to nearly $40 billion for Coach Factory Outlet almost 10 million students this year. His administration also made it easier to request aid, shortening the Coach Factory Online complex federal application and allowing people to transfer their financial information electronically from the Internal Coach Outlet Online Revenue Service database. But while many education experts laud his efforts, analysts of varying political Coach Outlet Online stripes have also questioned how much impact some of the president’s policies will have, noting that the prices Coach Online Outlet charged by colleges, and student borrowing, continue to climb.But behind the headlines about soaring costs, the Coach Factory Outlet Online reality is more complex and wildly uneven, because a growing number of students receive Coach Outlet Online financial aid, and only relatively high-income families pay those fast-rising sticker prices. Adjusted for Coach Factory Online inflation, the College Board calculates, the average net price changed little over the last decade at private Coach Factory Outlet schools, and rose only modestly at public ones.Defending federal spending, Arne Duncan, the secretary of Hermes Belts education, said that for more than 30 years, college prices had risen even when federal aid had not, leading him to believe Coach Factory Online there was zero correlation.
|
|
|
|
10-22-2012, 10:14 AM
|
#10 (permalink)
|
|
The Addict
Join Date: Oct 2012
Posts: 244
Thanks: 0
|
when I go home. Coach Outlet It’s a big part of what I find addictive about living and working in Coach Outlet Store Online this part of the world. You feel like you’re watching the future unfold. Coach Factory Online for the US Open with no success."I prefer to go day-by-day without setting objectives or Coach Factory Online time frames, work hard on my recovery and make sure I keep on getting better little by little."Nadal has been forced Coach Outletto watch from the sidelines as longtime rival Roger Federer returned Coach Purse Outlet Onlineto the top of the world rankings after winning Coach Factory Outlet Onlinea seventh Wimbledon singles title.He has also seen Britain's Andy Murray, Coach Bags Outlet Online who won the men's singles gold medal at the 2012 Olympic Games, move above him in the world rankings after securing his Coach Handbags Outlet first grand slam title at last month's U.S. Open.Currently ranked fourth in the world, Nadal has qualified to play at November's season-ending ATP World Tour Finals in London, Coach Outlet Onlinebut his ability to take part is in doubt due to his injury problems, admitting that his knee is still "bothering him".
|
|
|
|
12-07-2012, 11:41 AM
|
#13 (permalink)
|
|
The Visitor
Join Date: Dec 2012
Posts: 1
Thanks: 0
|
Thanks for giving useful codes. I was looking of this code for my next project so thank you very much. Web Software Outsourcing (WSO) company is a division of Hi-Tech ITO (ISO 9001:2008) based in India.
iPhone Application Development India
|
|
|
|
12-11-2012, 08:11 AM
|
#14 (permalink)
|
|
The Visitor
Join Date: Dec 2012
Posts: 1
Thanks: 0
|
Yes, This is good description about Abstrect class with coding. Thanks for share it over here so beginners can get solutions of this problem.
Hire iPhone Application Developers (HIADs) company is a division of Hi-Tech ITO (ISO 9001:2008) based in India.
Hire iPhone Developer
|
|
|
|
12-13-2012, 08:31 AM
|
#16 (permalink)
|
|
The Visitor
Join Date: Dec 2012
Posts: 4
Thanks: 0
|
To celebrate New Year, Christmas,and say goodbye "The end of the world",the lowest price this year for you:
http://www.msngoodsales.com cheap+good quality+free shipping made in china A&F,Adidas,Armani,Gucci,Boss,Burberry,Ck,Nike,Mk,P olo,The North Face,Versace,Fendi,Hermes.Ed Hardy...
1,Hot selling:hat&scarf,Various styles, high quality,lowest $12 warm your up.
work-konw brand bag only $25.88
2,Clothing-jacket,windcoat,T-shirt,suit,jean,skirt, pirce: $38-$120
3,Shoes,Nlike, Lebron James ,Jordan $43
4,Lady earring,necklace,bangle,LV,Juicy,Gucci,MK,Prada, only $40-$90,
5,Belt for armani.lv,hermes,burberry,DG,Gucci,prada,versace,e ach one only$22
|
|
|
|
01-29-2013, 12:52 PM
|
#17 (permalink)
|
|
The Addict
Join Date: Oct 2012
Posts: 244
Thanks: 0
|
Organizers said Coach Outlet Online was opportune because the battle’s 150-year anniversary is in December, and Fredericksburg Coach Factory Outlet has been preparing to mark the sesquicentennial. in the new agreement is that Coach Outlet Online revolutionary councils from 14 Syrian provinces now each have a representative, though not all live Coach Online Outlet in Syria. The hope is that will bind the coalition to those inside the country. Perhaps Coach Bags Outlet the most important body the new group is expected to form is a Revolutionary Military Council Coach Factory Online to oversee the splintered fighting organizations and to funnel both lethal and nonlethal Coach Factory Outlet military aid to the rebels. It should unite units of the Free Syrian Army, various militias Coach Outlet Store Online and brigades in each city and large groups of defectors. Before the ink was even dry on the Coach Outlet Store final draft, negotiators hoped that it would bring them the antiaircraft missiles they crave to Coach Factory Stores take on the Syrian Air Force. The United States and Britain have offered only Coach Handbags Outlet nonmilitary aid to the uprising. A similar attempt by the Syrian National Council to Coach Factory Store supervise the military never jelled. Organizers said funding was too haphazard. Eventually foreign Coach Factory Online governments like Qatar and Saudi Arabia, which are financing and arming the rebels, found Coach Factory Online their own favorite factions to deal with. Foreign leaders notably including Secretary of State Coach Outlet Hillary Rodham Clinton urged this unification largely so they could coordinate their Coach Factory Outlet efforts and aid through a group of technocrats. Once it receives international recognition, the Coach Outlet Store Online coalition is supposed to establish a temporary Coach Outlet Online military never jelled.
|
|
|
|
02-28-2013, 05:38 AM
|
#19 (permalink)
|
|
The Wanderer
Join Date: Feb 2013
Posts: 18
Thanks: 0
|
Abstract classes are classes that contain one or more abstract methods (methods without implementation). nice articles.
|
|
|
|
|
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
|
|
|
| Thread Tools |
Search this Thread |
|
|
|
| Display Modes |
Linear Mode
|
Posting Rules
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
HTML code is Off
|
|
|
|