The purpose of this article is to give a novice programmer the basic idea of what OOP is, as implemented using PHP. Readers should have a basic knowledge of programming ie what variables are, variable types, basic methods of writing comments, and how to enter code into a text editor.
Also, other programming languages will most certainly use different keywords and methods of doing things (like defining a class, labeling a variable, etc). Remember to look for the concepts in this article, and not to get caught up with semantical details.
To begin, it is important to stress that one of the core ideas behind OOP is that code written by the programmer is placed in reusable chunks. Reusable chunks of code save the developer time and money during the coding process, as well as making the code much more efficient. These reusable chunks of code are then used to create what we call an object; the object can be manipulated, made to do things, etc.
Before you actually “create an object,” you design the template for the object. This template is called a “class.” All code that the object does, and properties of the object are placed inside the class. As mentioned previously, I’ll be using PHP for demonstration purposes, as it is one of the quicker and easier coding languages to learn. Below is some sample code, which simply creates a class called “Student”:
PHP Code:<pre>
<?php
class Student {
}
?></pre>
The name of our sample class is “Student.” Classes are recognized in php by the “class” keyword. What we want to do is create the template for a typical “student.” The student can do things. Some of the things the student can do include: go to class, skip school, go to lunch, turn in homework, ride the cheesewagon (er bus), that sort of thing. Anything we want the typical student to be able to do, we put inside what is called a “function” (some languages call these “methods”, ie Java).Continuing with our example:
PHP Code:
<?php class Student { function goToClass() { } function rideTheBus() { } function skipSchool() { } } ?>
Ok great. Now our template has some basic actions that our student can perform. We don’t actually have the code inside of our functions, but we’ve created the functions.
Another thing that we want to give objects are properties. Every property we want assigned to the student is also placed inside the class. Properties might include the student’s name, their grade level, their gender, their schedule, etc. On to the example:
PHP Code:
<?php class Student { var $Name; var $Gender; var $GradeLevel; var $Schedule; function goToClass() { } function rideTheBus() { } function skipSchool() { } } ?>
Before continuing, I want to stress the importance of two definitions: instantiation and initialization.
Instantiation is when you actually create an object in your code. Remember that classes are templates, or definitions for objects, very similar to blueprints. Blueprints aren’t the actual house, but the design for the house. Instantiation is when you actually build the house in your code (or in this case, you create your student).
Initialization is when you first assign a value to a variable. I mention this definition here because novice programmers can easily be confused by the differences in the two words…it certainly doesn’t help that they sound very much alike!
Ok, back to the code. We’ve created some variables in our template. Unfortunately, nothing is actually assigned to the Student object; we just have empty variables. (these variables have not been initialized). You can assign values to variables in your class using the “this” keyword. Also, if you have a function called the same thing as the class name (“Student”), then when you create an “instance” of the object in your code (ie, you create a student in your application), then that function is called automatically, as soon as you create the instance of the object. This function has a special name, called a “constructor”.
I’ll get to the example in a second. I also need to mention, that functions can take “arguments” or “parameters.” These are values that are passed into the function. The function assigns these values to variables, which it can then use and/or manipulate. The values are passed in via the parenthesis of the function. Back to our example:
PHP Code:
<?php class Student { /* These are some of the properties */ var $Name; var $Gender; var $GradeLevel; var $Schedule; /* Constructor. Called as soon as we create a student (aka "instantiate the object") */ function Student($studentName, $studentGender) { $this->Name = $studentName; $this->Gender = $studentGender; } function goToClass() { } function rideTheBus() { } function skipSchool() { } } ?>
What did we do? Well we added a constructor, and we told it to accept two parameters. These parameters are assigned the variable names of “$studentName” and “$studentGender.” Now, these two variables can only be used INSIDE THIS FUNCTION. That’s called “variable scope”. The next two lines of code say “I want to take the values passed into this function, and assign them to the object.” What does that mean? Well it means that when you create the object now, you can access $Name, and $Gender. More examples…
PHP Code:
<?php include "Student.php"; $a_student = new Student("John","Male"); ?>
I kept it simple. The code above would be a new file, while we save the rest of our example in “Student.php” The first line just makes sure that our template (the class file) is accessible. The second line is where the magic happens. It creates a new instance of the Student object, and passes two values to it – “John” and “Male”. Recall that when we create an object, the object’s “constructor” function is called immediately. Our constructor wants two values, the student name and the gender. For that reason, we passed these values in as we created the object.
You create instances of objects in PHP using the “new” keyword. The syntax is as follows:
Code:
variable = new ObjectName(parameters)
So now we have a real-code, digital student. How exciting. What do we do with him? Torture? Detention? Hmm….these all sound good, but we’ll start simply, but displaying some information about him.
PHP Code:
<?php include "Student.php"; $a_student = new Student("John","Male"); print $a_student->Name; ?>
Everytime you access something in an object you create (in PHP), you use the “->” characters. Some programming languages use periods. It depends on the language. (As an example, if you created that same object in JAVA, you’d print the “$Name” property by typing:
Code:
System.out.print(a_student.Name);
(In Java, you use “System.out.print” instead of just “print”, like in php).
So we have now have a Student object. How do we make him do the things we created in our template? (ie the functions). Well once you’ve added some code to the functions, you can make the object perform those function by doing the following:
PHP Code:
<?php include "Student.php"; $a_student = new Student("John","Male"); print $a_student->Name; $a_student->goToClass(); ?>
That last line tells the Student object to call the function goToClass(). Poor John. I’m certain he doesn’t want to go class. Now where’s the benefit of the function? Recall that OOP gives us access to reusable chunks of code. What if you wanted to create lots of students? An example:
PHP Code:
<?php include "Student.php"; $a_student = new Student("John","Male"); $b_student = new Student("Mary","Female"); $c_student = new Student("Larry","Female"); print $a_student->Gender; print "<br>"; print $b_student->Gender; print "<br>"; print $c_student->Gender . " " . $c_student->Name; ?>
That code creates 3 students. It then prints out the first two student’s genders. It then prints the third student’s Gender and his…er….her name. (I blame that on Winamp…Culture Club just started playing…..) Are you starting to see some of the benefits? You could then make b_student goToClass, and maybe have c_student skipSchool. These are spiffy things your program can do. Of course, you could write a “changeGender()” function…which seems to be particularly appropriate in the case of Larry…. It might look something like this (remember that this is a “Student” function, so this code goes inside the class. Also note that when I put ‘…’ before and after code, it means code exists before and after, but I’m not going to retype it all. Just stick this function somewhere inside your class, maybe after the skipSchool() function.)
PHP Code:
... function changeGender() { if ($this->Gender == "Female") { $this->Gender = "Male"; } else { $this->Gender = "Female"; } } ...
Hehe. Place that code in the class, and whenever you want to perform a sex change in your main code, just do something similar to the following:
PHP Code:
.. $a_student->changeGender(); ..
Now, any function can accept parameters, you just add that to the class, and then when you call the functions, you pass the values in. Let’s say we were to rewrite our “rideTheBus()” function to the following:
PHP Code:
... function rideTheBus($busNumber) { $statement = $this->Name . " rides bus number " . $busNumber; return $statement; } ...
then in your main program code:
PHP Code:
.. print $a_student->rideTheBus("65"); ..
So what did we do? well in the rideTheBus() function, we told it to accept a value, and place it into the variable $busNumber. We then created a statement that says the student’s name, followed by the words “rides bus number” and then the value placed in $busNumber. The return statement says that when that function is called, return the value in $statement to whatever called the function. We then passed bus number “65” into the function. The result of the above code would be to print out the following:
John rides bus number 65.
Now, there are other ways of printing the results of the function. In our main code, we said “print the value RETURNed by the function rideTheBus(). We could have done this:
PHP Code:
.. $busRideStatement = $a_student->rideTheBus("65"); print $busRideStatement; ..
This code does the same thing, but first dumps the sentence into the $busRideStatement variable, so we could reuse it later by just calling the variable, rather than having to recall the function. The complete code of what we did is below:
File: Student.php
PHP Code:
<?php class Student { /* These are some of the properties */ var $Name; var $Gender; var $GradeLevel; var $Schedule; /* Constructor. Called as soon as we create a student */ function Student($studentName, $studentGender) { $this->Name = $studentName; $this->Gender = $studentGender; } function goToClass() { } function rideTheBus($busNumber) { $statement = $this->Name . " rides bus number " . $busNumber; return $statement; } function skipSchool() { } function changeGender() { if ($this->Gender == "Female") { $this->Gender = "Male"; } else { $this->Gender = "Female"; } } } ?>
File: index.php
PHP Code:
<?php include "Student.php"; $a_student = new Student("John","Male"); $b_student = new Student("Mary","Female"); $c_student = new Student("Larry","Female"); print $a_student->Gender; print "<br>"; print $b_student->Gender; print "<br>"; print $c_student->Gender . " " . $c_student->Name; print $a_student->rideTheBus("65"); $c_student->changeGender(); print $c_student->Gender; // this will print "Male" now... ?>
That is the basics of OOP in a nutshell. The terms you should be familiar with include: parameters, functions, class, constructor, variable scope, return statements, instantiation, initialization.
Again allow me to reiterate that this article/tutorial is by no means comprehensive. Some advanced topics include: passing by reference, destructors – (just a special function, called when you destroy your object), polymorphism, inheritance, and default values. I am also quite sure there are other terms I’m not remembering right now, but the basics of how OOP works is all there.
I hope that for the novice programmer interested in learning the concepts of OOP, I’ve generally explained some of the basics. Remember that if you’re programming in a language other than PHP, the core concepts of OOP are still the same! You sill create reusable chunks of code, pass values to functions, and access properties of your objects. I’d like to encourage you to try writing a sample class of your own, and creating your own objects. It is your code, you can do whatever you want! I created a female student named Larry and was able to quickly give him a sex change…try doing that in real life! For those interested in using the php example I’ve created above, but don’t know how to get started using php, I highly recommend heading over to www.php.net . Windows users may also wish to take a look at www.firepages.com.au , where a very nice man has taken the time to bundle everything in an easy-to-use zip file, so you can get started coding quickly, without the hassle of setting up PHP. On that note, I shall throw away my now empty bottle of Mt. Dew, close trusty winamp, and bid you, the reader, adieu.
About the Author:
John Collins has been writing code for almost 20 years, since he was 5 years old writing in BASIC on his Commodore64. He enjoys coding, sports, and reading. He currently serves as lead developer, webmaster, and computer technician for a school division in Virginia, USA.
If you would like to see your thoughts or experiences with technology published, please consider writing an article for OSNews.
Does PHP 4 or 5 support classifying variables as private, or any other type of restriction to enforce encapsulation/abstraction?
well, php5 😉
Yes and no.. PHP4 doesn’t has them, but PHP5 has them. You should read the great article about PHP5 at http://www.sitepoint.com/article/coming-soon-webserver-near/ . In the five page, there have about public, private and protected.
Anyway, I usually like to do this:
$statement = “{$this->$Name} rides bus number {$busNumber}”;
instead this:
$statement = $this->$Name . ” rides bus number ” . $busNumber;
Thanks. What is the significance of enclosing a variable with brackets?
It might be an advantage to learn an OO programming language before any other, at least if your main interest is in writing applications (as opposed to libraries, where procedural languages hold the advantage). I know some good C programmers who can’t quite get into the OO mentality, because they’ve already learned one way of doing things which is “good enough” for them.
A similar situation occurs in learning to type. If you started out with the “hunt and peck” method (like I did), it’s really difficult to switch to touch typing. Especially if you can hunt and peck at a “good enough” speed. So inertia can be your enemy.
“happy {$hippos}!” is the same as “happy ” . $hippos . “!” in PHP.
Also, variables “should always” (at least it’s a standard) be written in lowercase, such as $name and $genderLevel instead of $Name and $GenderLevel.
OOP programming with PHP is nice…but PHP isn’t fully OOP. Some OOP features like Object Overloading are missing. (altrough some dirty hacks exist). Using OOP can improve security (especially with PHP5) if it’s done the right way.
It’s also important to realise that PHP4 uses value-semantics (as opposed to the more usual reference semantics) for objects. Thus if you say
$bill = new Student(“Bill”, “Male”);
$william = $bill;
three objects will be created. The new command creates an object, and then a copy of this is placed in the variable $bill. On the second line another object is created (a copy of the one in $bill) and is placed in $william.
Thus for the following
$bill = new Student(“Bill”, “Male”);
$william = $bill;
$bill->name = “Bill Gates”;
echo $bill->name . ”
“;
echo $william->name . ”
“;
You would get
Bill Gates
Bill
This becomes even more of an issue in functions. As a result most PHP programmers explicity pass by reference.
The following code passes by reference
$bill =& new Student(“Bill”, “Male”);
$william =& $bill;
$bill->name = “Bill Gates”;
echo $bill->name . ”
“;
echo $william->name . ”
“;
and the output is
Bill Gates
Bill Gates
In PHP5 objects will use reference semantics only, and there will be no need for hundreds of & symbols in your code.
One of the main featurs in OOP, is the concept of a class as a blackbox. One should not know what is inside the class, or how it is implemented. Thus instead of accessing the data directly trough $person->name it would be much cleaner to have getter/setter for that variable, fe: getName() { return this->name; } and setName($name) { if isValid($name) this->name = $name; else raiseError(“invalid name”); }
for an introduction to OOP, PHP is not the best option. a beginner (like myself) is confused by the web-related side of it.
what has <? got to do with OOP?
pyhton would be a much better introction to OOP, or even programming in general.
So your saying that just because Java does it this its bad and you should flame the person? Even if this practice JUST MAY be a better way to do it?
Maybe you don’t need explicit get/set methods but the original post was right. When programming to a class you shouldn’t need to know/care about how that class does it stuff.
By the way you shot back at him I’m guessing you leave all your variables as public globals so anyone get at them?
Also, why would “Java mentors” think multiple inheritance is evil? Care to explain?
I agree that introducing the web aspects on top of learning OO is a bad idea. You need to learn a more general scripting language like Python or Ruby that you can install and learn right away.
PHP is a good choice, it’s easy to learn with clear syntax.
You really don’t need to create web-based application with PHP, you can do console, even GUI applications. I’ve written several phpgtk apps with php/gtk and especially looking forwards php5+gtk 2.0 support.
Developing Script languages is much faster than compiling c++ for example, which makes it especially good for learning.
I write PHP as my work and I can tell you, PHP has really nice OO features and makes possible to develop OO code very fast. Of course, lots to improve, but PHP5 with Zend engine 2.0 brings really good OO capabilities.
You’re referring to Python. Do you even know Python syntax or have even coded in python? Python syntax, in my opinion, is very ugly. Horrible ugly. PHP syntax is quite near C++ and Java, which makes learning them easy in the future.
Just my opinion.
The whole “getter” and “setter” thing is not necessarily the only way to go. For example, C# has the concept of Accessors, which makes it “seem” like you are accessing properties directly, but in fact every request of a property gets passed through the method(s) of your choice anyway.
Think of it like having triggers and constraints in an SQL database. Even though the query is simply getting or setting a database value, the system intercepts that query and performs additional or substitutional logic.
Fortunately, PHP allows for this with the Overload extension (http://php.net/overload), which is available in PHP4 and PHP5.
I want to commend the author for this article. I’ve done lots of work with PHP but never using object-oriented methods. I’ve been learning C++ but the concept is sometimes overwhelming until you’re used to it.
This tutorial offers a good way to start using objects in something I’m already comfortable in, namely PHP. True, PHP might not be 100% OO but it makes a great stepping stone to learning to do it in other languages.
Thanks for a great article, John!
When using variable interpolation in PHP (which occurs automatically with double quoted strings but not with single), the braces act to disambiguate variables from the surrounding text.
Example:
$foo = ‘spam’
$bar = ‘$foo to you’
$wrongbaz = “$foos to you”
$baz = “{$foo}s to you”
echo $foo, $bar, $wrongbaz, $baz
Should print:
spam
$foo to you
$foos to you
spams to you
Notice that it’s impossible to tell whether you mean to look up the variable $foos or whether you’re trying to add an ‘s’ onto variable $foo, hence the need for braces.
You’re referring to Python. Do you even know Python syntax or have even coded in python? Python syntax, in my opinion, is very ugly. Horrible ugly. PHP syntax is quite near C++ and Java, which makes learning them easy in the future.
Just my opinion.
I code in Python as my primary language. Having coded in all the languages you list (PHP, C++, Java), I find Python’s syntax to be the best. The lack of extra control characters like braces, semicolons, and dollar signs make the code easier to type and read. I can skim other people’s code without getting worked up about brace placement and whatnot since the compiler-enforces one coding style.
I find PHP, along with perl, to be one of the uglier languages, the $variable convention irks me for some reason. It does allow you to get a lot of web programming done, though, and that’s why I use it.
Just a counter opinion. ;]
I don’t have any particular antipathy towards Python, but I have to say, I personally really like the ‘$’ prepended on variable names, and I think PHP’s nice simple way of dealing with that is much nicer than Perl, Bash, or TCL, for example, where there are ungainly additional rules as to what prepends a variable. It makes it easy to tell at a glance what is a variable in your code.
That, combined with 1) the ease of variable interpolation in strings via {$varname_or_expression}, 2) the concept of variable variable names, as in $$varname, and 3) even the concept of variable (conditional) function execution via $function_name() all combine to create some powerful scripting features.
python’ syntax is agonised over.. it is one of its best design goals. and python’s inheritence (if you’ll excuse the pun) is in languages designed to teaching to younger minds…
About the only thing OOP and PHP share is the letter P. Ruby would have been a far better choice to learn OOP from.
I agree with everyone else’s assertion that PHP isn’t a good place to start learning OOP. I learned OOP at the university level and they started us off with Java. I still think that is the best place to start because it is syntactically very similar to C. Ruby and Python are good examples of OOP languages, but they both have non-traditional syntax.
Unless you yourself sit down and right an equivalent, easily read, easy to comprehend little tutorial in language X. If Ruby, Java, Python, D, whatever, is better for doing what the author attempted to do- go ahead and contribute.
If you wish to discuss the pro’s and con’s of the various languages and their differences- please do so by all means, particularly if your post actually provides insight into non-obvious things for those who don’t already know the language in question-otherwise you are just playing ego-games….
(kudos @ rycamor and @Anonymous (IP: —.res.gatech.edu) and @ Bryan Feeney )
If you declare a property in your class such as var $Gender; then you must access it through $this->Gender or $object->Gender, not $this->$Gender or $object->$Gender
If $Gender is a local variable and has a value, (say, “name”), accessing $this->$Gender will effectively access $this->name.
Say for example I do this:
class Student {
var $gender;
var $name;
function blah() {
$Gender = “name”;
$this->$Gender = “Male”;
echo “Gender: ” . $this->$Gender; // Will print “Male” indeed.
}
}
$s =& new Student;
$s->blah(); // will print “Male”
echo $s->gender; // Will not print anything
echo $s->$Gender; // Will not print anything
echo $s->Name; // Will print “Male”;
The lesson here is that you should never use the dollar sign to refer to an object’s property. Whether it is to set it, or to retrieve it.
The article uses them for every single property and this is not the proper way to refer to instance variables at all.
The proper way would be as follow:
class Student {
var $gender;
var $name;
function blah() {The article
$this->name = “Blah!”;
$this->gender = “Male”;
echo “Gender: ” . $this->gender; // Will print “Male”
}
}
$s =& new Student;
$s->blah(); // Will print “Gender: Male”;
echo $s->gender; // Will print “Male”;
echo $s->name; // Will print “Blah!”;
This process is also highlighted all over the place in the php documentation.
I think an errata is required here.
I learned OOP at the university level and they started us off with Java. I still think that is the best place to start because it is syntactically very similar to C. Ruby and Python are good examples of OOP languages, but they both have non-traditional syntax.
If your primary reason is syntactic similarity to C, then you should be telling people to start learning OOP with C++, considering that it began as a superset of C, and that C programming is still completely possible with many C++ compilers.
The problem many people have when moving from C to Java or C++ is breaking the mindset that programming in C often brings with it. This is why learning OOP is often better done in a language with a non-C-like syntax to get the ideas firmly rooted in the mind of the programmer, and then let them learn the OOP syntax of C++ or Java, where they can return to familiar coding styles with the OOP ideas fresh in their minds.
Sticking with one familiar syntax for every piece of code you ever write doesn’t really help you in the long term. Over the last 5 years I’ve had to learn 4 programming languages, 2 of which had C-like syntax, and 1 of which was similar enough to a C-like syntax to get by. In the end, I found the 1 language that did not use C-like syntax was what got the job done for 3 of those 5 years, and in the last 2 years I’ve had to use a blend of C, C++, and C# to get what I needed. I certainly prefer these languages, probably because C was the first language I learned (8 years ago), but I often find myself looking to other languages to learn new concepts, even if they’re available in one of these C-based languages, simply because it’s easier for me to pick things up at the conceptual level when I’m not trying to use familiar syntactic elements in new ways.
I have written a few classes in php, and for me they’ve been a useful way to have a collection of related functions share variables between each other. But, I don’t know enough about OOP to fully grasp all the objections that I always hear raised when php & OOP are mentioned together.
I think we could spend all day arguing about what language would be best to teach OOP, but then we’d be missing the author’s intent. I was taught OOP @ University using Java as well, but never could quite grasp the general model of OOP. I think this article does a pretty good job of demonstrating OOP basics, even if some mistakes were made in the exact implmentation/demonstration of it.
A java tutorial might have been best, at least then visibility modifiers would have been included for variables, but as a PHP developer as well, I can certainly see the “Simplicity” benefits of using PHP.
Python, one of the saner languages I have come across. I find I can do a lot of work in Python very quickly, although the efficiency of such results means the quality can only ever be prototype-level. For brainstorming, scripting and testing ideas, Python is unmatched. I hope that bringing Python to the .NET CLR will make it more efficient (compiled to native code at load/run time) and therefore more useful. Python has the potential for fully-blown web and GUI applications.
Personally, I hate syntax, it is a foolish distraction that brings intelligent people to a level of religious blindness. The truth is, semantics is all that is important in a language. Python takes a decent compromise of cut-down syntax, but enough to make code easier to comprehend.
OOP sucks but Python does it well 😉 It should be great for teaching OOP, I imagine.
PHP is nearly worthless as an OO language as it really isn’t OO, it pretends to be by offering a class structure with very simple inheritence.
PHP is not strongly typed and it is interpereted, therefore it is probably one of the worst choices to explain OOP.
What about design patterns? What about building real-world business objects and mechanisms to deliver them to your presentation layer (i.e. facades, visitors, etc.)
PHP teaches you poor OOP practices by munging your programming logic into your presentation layer, otherwise known as spaghetti code.
For *real* OOP learning, turn to ASP.NET or Java, where you have strongly typed languages, interfaces, full inheritance, and tons of other constructs (class libraries, stateful objects, etc.) in order to learn OOP to its fullest.
I concur whole-heartedly, that another language could have been used. I think for the purposes of introducing OOP to a beginner however, PHP’s basic OOP implementations are more than sufficient. PHP’s OOP model is loosely based off of Java (I think, certainly looks that way).
I’ve read countless articles saying “You should learn in <insert language>.” To reiterate, the spirit of the article is to teach basic concepts, not to teach a language. In that regard at least, the author did a decent job, I think.
Bah… whether a language is strongly typed or interpreted has nothing to do with whether it is OO. That is like complaining that Perl isn’t compiled, so it is not procedural like C. In fact, there is no clear formal set of rules as to what exactly defines an OO language. This even goes down to such things as prototypes vs. classes, function nesting, etc…
Of course, no one in his/her right mind would argue that PHP4 is a very complete OO language, but PHP5 actually offer almost all of the things you refer to, including the ability to restrict automatic type conversion. (http://zend.com/php5/articles/engine2-php5-changes.php)
What you are really talking about is not OO, but general language design goals. PHP is designed as a scripting language. Scripting languages in general are weakly typed, and allow for such interesting things as dynamic evaluation, etc… In fact, there are some very logical arguments FOR weak typing in scripting languages, as argued by the creator of TCL. PHP is not meant to be the language for serious “business objects” (Personally, I’ll keep my business logic in the database, for the most part, but PHP can easily interact with many “heavier” systems where an enterprise might keep its core business logic)
PHP doesn’t “teach” you to combine logic and presentation. It leaves the choice up to you. With PHP, I haven’t munged business and presentation together in years.
Sorry for the rant, but I’m tired of hearing all the same tired old arguments.
Unless you yourself sit down and right an equivalent, easily read, easy to comprehend little tutorial in language X. If Ruby, Java, Python, D, whatever, is better for doing what the author attempted to do- go ahead and contribute.
Whoa! Take a deep breath and calm yourself. It’s just a sharing of ideas. It’s good to write a beginner tutorial about OOP, but the criticism of using PHP as an example is certainly valid. It does lack many of the structures that are fundamental parts of OOP. Furthermore, it’s a web-based scripting language.
But on a different note, I must say that I love the fact that PHP is object-oriented. Especially the new features that are being implemented in PHP 5. With web-apps becoming more complex, it is a major advancement to offer a server-side scripting language that bears a greater resemblance to true OOP languages.
While its true that PHP was originally created with the sole purpose of being a web-based scripting language, I would argue that over the past 2 years it has pretty much graduated to general scripting language. Especially for Unix systems, it includes all kinds of capabilities for systems-level interaction: sockets, streams, process control, expect, readline, FAM, direct I/O, shell redirection, and a long list of other shiny toys ;-).
For example, I have just finished a project on FreeBSD using PHP in daemon mode, as a socket server for messaging, and it has been rock-stable. Nothing at all web-based about this project.
And, all of these abilities will be even better integrated in PHP5. I am really looking forward to it.
but 99% of the time, I don’t get why OOP is better than plain old procedural functions in PHP.
How is this any easier? Is anything “more reuseable?” It seems like classes are just way more typing than regular non-OOP functions.
“A PHP Beginner’s Crash Course into Object Oriented Programming, part 1 of n”
There isn’t a concensus on what OOP is about, but generally encapsulation is only the tip of it. IMHO polymorphism is the key to OOP, without which OOP does not have significant advantage over procedural programming.
And Python is a much better first OOP language to learn. Depends on your background or interest, you can also learn Squeak Smalltalk or Objective-C.
You’re not clueless. I’ve never done PHP, but I’ve done a lot of C++ and quite a bit of C#….a little Java. OOP has it’s uses but it’s been oversold – especially it’s reusability in comparison to procedural code.
In reality not everything has to be in a class, but could just as easily be a standalone function in a particular namespace to avoid namespace collisions. I like how c# v2.0 will introduce static classes so you don’t have to prefix all your variables and functions with static in the class, but I still don’t see why you can’t have a standalone function in a particular namespace. Maybe it’s a compiler issue. I don’t know
I tend to agree that OOP has been oversold, especially for the past decade. However, the pragmatic in me finds many uses for it. In fact, I would argue directly in opposition to Traal‘s post at the beginning of the thread. I think libraries are the most natural place to use OOP. (of course, we might mean different things by the term ‘library’)
For example, in PHP, HTML templates fill a very useful problem space. They don’t solve all problems of logic/presentation interaction, but they are quite useful. Keeping your template logic inside a class makes it easier for templates to be widely deployed, even by people who have no idea what is going on inside the template code:
———
require_once(templateClass.php);
$mypage &= new templateClass(‘/path/to/template.html’);
//.. whatever complex logic I use to arrive at a value for $variable
$mypage->assignVar(‘MARKER’, $variable);
$mypage->render();
———
Now, if I had to do the same thing without OO, it would have to look like:
———
require_once(templateFunctions.php);
$mypage = startTemplate(‘/path/to/template.html’);
//other app logic…
assignTemplateVariable($mypage, ‘MARKER’, $variable);
//oops, now you have to pass $mypage by reference inside the
//function, so you modify the main $mypage variable and not a copy
//or, you have to constantly return the modified variable in full,
//as in $mypage = assignTemplateVariable($mypage, ‘MARKER’, $variable);
//which can be dangerous and counter-intuitive
//and you have to do more namespace-collision checking
———
So you see how sometimes procedural methods can introduce unnecessary distractions in your main app flow. Even if your main application flow is procedural (which has its advantages in clarity and readibility), “side” issues like your database access and presentation concerns can be handled by classes. Basically, anything that you would like to swat aside like a fly, because it annoys you in your code could benefit from being encapsulated in a class somewhere.
Some of my criteris for the kinds of things to hide in classes tend to be:
1. if I am dealing with something annoying that distracts from my app flow, such as dealing with HTML, or configuration settings, etc…
2. if I want to maintain or protect the state of something I am dealing with — for example, I have a class to access windows networks from Unix with by calling ‘smbclient’. Now, that gets really messy, because each call to smbclient leaves you back at the root directory, so it is hard to navigate directory hierarchies in code. But, I maintain that state inside the class, using extra methods to put me where I should be each time, so the rest of my PHP code can interact with a Windows LAN just as naturally as with a local directory tree.
3. As a way to wrap up and render harmless some particularly messy piece of code inherited from a previous developer ;-). Haven’t we all been there…?
4. When I want to think of a certain collection of data as sort of a ‘complex’ data type, which can be wrapped up and passed anywhere. Try that with only functions and you will get a headache fast (although it can be done).
Don’t let anyone sell you OO purity as some sort of magic, but by the same token, don’t be so quick to dispense with it. There are all kinds of reasons to use either one of procedural, functional (and yes, PHP has some functional abilities), and OOP. Really, I think each of us has certain mental predispositions to one or the other, but it is a good idea to learn a range of possibilities, so you can make an informed decision about which to use where.
I, quite franky, agree. OOP has niches where it is appropriate. But you are better off with procedural programming for the web. From what I can gather, PHP is often teamed up with MySQL, so there is no need to carry state inside objects when you have a database right next to you!
With a class you have reduced the reusability of all the functions (“methods”) by locking them to a certain type of data structure. This may, in the short term, make them easier to use; but the lock-in nature dooms them to obscurity.
Combined with the fact that there are so many different OOP ABIs, and so many different opinions on whether feature X or feature Y are considered “OO”, code re-usability is simply unfeasible (at least across language boundaries). Procedural code, with handles for state tracking when (and only when) it is required, is more often than not sufficient for almost anything. This is one reason for the persistence of the C language, despite all its failings!
Well, I had the same question. It seems there are some applications that could use a little polimorphism (nothing vital, however).
For instance you could define a “html rendering engine” of some pages as an “abstract class”. Then write code having this “interface” in mind. Then write some implementation (actually generating the html, implementing the interface).
Nothing fancy yet.
But suppose you want to change the look of the site. You only need to write another implementation and create an instance of the new one instead of the old when needing a renderer (hopefully the renderer is created only once, in one place). This separates look&feel code from the rest of the app: the rest is written (hopefully) with the renderer interface in mind, so changing implementations doesn’t matter.
Switching site looks becomes easier. Well, if you need that sort of change
I’m sure similar stuff can be imagined. OOP is useful, sometimes ..
Personally, in defense of object oriented programming, I have to say that it’s made my life eaiser, in most cases (where it is appropriate to use).
It doesn’t solve every problem every time one is presented, but such is any programming language or technology and…such is life.
It wouldn’t be practical to sit down and say “I only know or like C++, so I want to write a web site in C++” and then continue to sit down and write a simple web site by using C++ (I know the example is farfetched but it’s also a possibility). In this particular situation, you would use HTML and perhaps combine that with other web-centric technologies such as CSS, JavaScript, or on the server side Java, C#, and perhaps even some C++-based web services.
A few years ago I wrote quite a bit of code in ASP/COM and other web-centric Microsoft technologies.
In procedural ASP (using say, VBScript), I would tend to write a TON of the same type of code repeatedly and it grew quite difficult to maintain in larger projects. Even writing VB COM components posed a lot of problems with maintainence issues.
Now, for example, using ASP.NET and .NET assemblies to contain highly OO code, I’ve found my projects easier to envision, plan, test, build, and maintain.
Rather than grabbing a Recordset and repeatedly looping through it over and over and over to display data (spaghetti-coding it together with HTML) I can now create a clean, simple business object to represent my data, populate it with data using the appropriate design pattern, and display it on the client very easily with data-binding.
Should I want to do something particular to each record after it’s bound, I can simply extract it with an event-handler
Product product = (Product)e.Item.DataItem;
product.Name
product.Price
…
…and then do whatever I like with it’s methods and properties.
It’s a beautiful thing, I’m a big OO proponent for most programming tasks!
However, it does not solve every problem and for small web sites, applications, etc. – procedural works just fine and in that sense, will never go away or be considered obsolete.
Just my $0.02!
With a class you have reduced the reusability of all the functions (“methods”) by locking them to a certain type of data structure. This may, in the short term, make them easier to use; but the lock-in nature dooms them to obscurity.
Right on, and this is not discussed enough. I know this is not really a problem with OOP – per se, and can be mitigated with refactoring, but this is a problem with re-use. Software artifacts should be loosely coupled with tight cohesion. When you throw everything in a class you end up with tight coupling a lot of the time.
>With a class you have reduced the reusability of all the >functions (“methods”) by locking them to a certain type of >data structure. This may, in the short term, make them easier >to use; but the lock-in nature dooms them to obscurity.
Isn’t this like saying that it sucks that my
ford passenger door can’t be used on my toyota?
You really think they should be reusable across
products?
The issues are the same in OO. At some scales in some
contexts reuse makes sense. It many others it does not.
This is not doom. This is the reality of things designed
for a purpose.
I guess you have a point there. There probably is no point in making public functions that muck about with internal state. In that case a class is a convenient way to hide it away. And I also guess that genericness of a function is not always desirable (because it may be a lot less efficient).
This really depends on the kind of code you are writing. It is probably inconsiderate for a library designer to dictate which structures you should use. Calculating a person’s age from a date of birth and the time() doesn’t need a Person object! (bad example, can’t think of a good one at the moment)
One interesting area in all of this might be the concepts of Aspect-Oriented programming (AOP). It seems to me the point of AOP is to resolve precisely those method lock-in issues of traditional OOP. It takes into account the idea that some concerns are “crosscutting” to others, and thus should be employable across classes instead of encapsulated in them. Anyone with experience at AOP care to comment?
It’s usually at about this point in a discussion where I bring up my favorite logical model: the relational model. By that I mean the “true” relational model, not the standard hack called SQL.
Now I understand the relational model is not a programming model, but a data management model. However, most of the problems of programming ARE data management problems. To me, the interesting point about the relational model is precisely that it handles problems such crosscutting concerns simply and elegantly, allowing for declarative constraints over any and all parts of the system, allowing for user-defined operators, operator overloading, etc… Also, the relational model theoretically can allow for datatypes of arbitrary complexity, even inheriting attributes from other datatypes. It seems to me almost that by the time we have come full-circle with some magical combination of OOP, functional/declarative, AOP, etc… we might finally have what the relational model has had all along (only no one has bothered to implement it). And, yes… I will now bring up the website some programmers love to hate: http://www.thethirdmanifesto.com ;-).
By writing my common utility functions in nice, well contained classes, I have found that it makes it much easier to work on a project. For example, I wrote a class that interacted with MSN Messenger, and I abstracted away all of the socket stuff into it’s own wrapper class. When I was assigned to write a project that monitors an IMAP mailbox, a nice sized chunk of this project was already done! I can just write a new class called IMAPMailNotifier or whatever, and use include SocketWrapper as a member, and now I have instant socket functionality. If I ever need to do MD5, url-encoding, I also have those classes available now. A week later, I was asked to write a project that parsed the Spam folder of an IMAP account, and parsed a header (X-Spam-Header- spamassassin score) and gave an average score for all of the message. It only took me 30 minutes because I had a reusable IMAP class.
Yes, this does mean the original project took longer to do, because I had to spend some time organizing the classes, seeing how they would interact with each other, deciding what members should be private, if anything should inherit anything from anything else, but it pays off. I have easily reusable code. My employer certainly was impressed at how quickly I finished my projects, and it also means that I have to spend less time debugging my project, because I am using code I have already tested.
Just my thoughts!
>One interesting area in all of this might be the concepts
> of Aspect-Oriented programming (AOP). It seems to me the >point of AOP is to resolve precisely those method lock-in
> issues of traditional OOP.
I think the logical conclusion of AOP is that methods
and classes do not exist. Otherwise what does my method
or class mean anymore if anyone can change it to do
anything and i can’t even tell that it happened?
as someone new to oop, why would you use class Student, then turn around and make a function Student.. i have no idea what you are talking about when you refer to $a_student = new Student(fdsa,fdsaf); ….
Would anyone be interested in seeing a similar tutorial done in modern Fortran?
In all seriousness, I’d be quite interested in doing so, as that’s a language that’s not oft-mentioned in these circles. A little breadth-of-experience could be interesting for many readers here.
from what I understand AOP allows you to define actions based on aspect rather than class. most of the examples I see involve things like data input or record handleing and verification. AOP allows you to define something accross all classes of a type you define. The examples I always see are error & bounds checking…AOP allows you for example to define bounds checking for ALL input fields…preasent and FUTURE…so you can’t forget to add it later! It’s just there in the background doing it’s thing.
The poster above was right about the relational thing, everything is data & scripting is just stored procedures on the data…we’re working both ends against the middle here. There are rules-based database applications that take general rules and apply them to make applications…but programming languages haven’t quite bridged the gap to make it have a human’s intuition…simple things users might want such as “all screen will input employee clock number” are still a bear to implement in most programming languages. especially AFTER the programs are already running!!!
as someone new to oop, why would you use class Student, then turn around and make a function Student..
When you make a function with the same name as the class name within the class, this is a special function called a constructor. This function is called when an object of the class is created. Remember that the class is a guideline for making objects. This is explained in the article…
i have no idea what you are talking about when you refer to $a_student = new Student(fdsa,fdsaf); …
$a_student is an an object of class Student (if you want to be more fancy, $a_student is an an instantiation of class Student). We designed a class called Student, and now we are actually creating a Student by using new. The fdsa,fdsaf are values that are passed to the constructor.
well after doing some reading, he should have mentioned that the reason he named the first function Student is because that is what is looked for first considering the class is named student, at least that is what i could get out it from other readings.
Also, if you have a function called the same thing as the class name (“Student”), then when you create an “instance” of the object in your code (ie, you create a student in your application), then that function is called automatically, as soon as you create the instance of the object. This function has a special name, called a “constructor”
It is in the article.
Would anyone be interested in seeing a similar tutorial done in modern Fortran?
What do you mean by “modern Fortran”? The currently used standard, Fortran 95, is no OO. OO programming can be approximated (I personally did it, developing a whole library in Fortran 95 using an OO-like structure with private types put in modules and getter/setter functions to access these types), but it’s very much like Perl 5’s OO: a hack to simulate OO programming in a procedural language, and it’s not easy to maintain.
Fortran 200X will be completely OO, but the standard is not ready yet and no implementation exists of it.
In all seriousness, I’d be quite interested in doing so, as that’s a language that’s not oft-mentioned in these circles. A little breadth-of-experience could be interesting for many readers here.
I agree. Fortran *is* a nice language, which has evolved a lot since the days of Fortran 77 and fixed-form lines. Fortran 95 is a very modern programming language, with an interesting syntax (although it sometimes annoys me to no end ) ). For heavy array calculations, Fortran stays the best language out there (which is why one of the best fluid mechanics simulation package out there, Fluent, is written entirely in Fortran) and with the right libraries, it can do many other things (I personally write programs with full GUI entirely in Fortran, thanks to the Winteracter library). Fortran 200X will have complete access to the C libraries, thus providing tons of useful features without need for rewriting.
In my hierarchy of favourite programming languages, Ruby is the uncontested winner (being the first language I saw that seems to *guess* my needs before I even articulate them ) ), but Fortran is a good runner-up, probably because it took me only three weeks to learn enough Fortran 95 to be productive (without formal course). Only Ruby has a better score here (I’ve had formal classes of C and Pascal, and tried to teach myself Java and Python, but never managed to get productive in those). And note that I am *not* a programmer by education, but a engineer (in my current job, I am slowly becoming a programmer, though, which is why I had to learn Fortran ).
Anyway, I agree that an introduction to Fortran 95 would be a good idea (if only to dispel the myth that Fortran is outdated ). I could help if needed.
Sure, I would be interested in a Fortran tutorial. Funny… the last time I dealt with Fortran was my first year of college (1983… yeesh), and I as 17-year old engineering student took an intro to Fortran course. Back then, the Freshmen didn’t even get to work with CRTs, so we had the experience of typing our code on punch cards… lol. My main project had a bug that neither I nor my professor could figure out. She finally gave me a good grade, because as far as she could see, my code was right, but the mainframe just refused to run the program. That experience soured me on programming for quite a while, unfortunately.
My main thought, to which I’m sure you’ll agree, is that everything object-oriented presented in this tutorial is also available in modern Fortran. And yes, I do mean Fortran 90/95 when I say modern.
As far as if F95 is and OOP language, well, more or less it is. There are some excellent tutorials on this and even the book _Object-oriented Programming with Fortran 95_, which is pretty decent. What Fortran 95 cannot do is dynamic dispatch (i.e., part of what templates allow in C++) and inheritance. Both of these can be emulated to a degree if they are absolutely necessary. Of course, as you mention, the Fortran 2003 (official name) revision updates the language to a fully OOP language. If you wish to play with these things, the current Lahey compiler (version 9?, I’m not sure), already impliments many of the new features, including OOP features.
Hmm, on second thought, it may be pretty cool to write a pretty simple intro to OOP and F95, and then play with the Lahey compiler to flesh out an intro to OOP in F2003. That could be really fun.
This was probably one of the most easy to understand OOP breakdowns I’ve ever read.
Great Work. Maybe Oreilly should give you a book deal!
-Nx
Thanks!
Excellent artcle.
I’ve struggled with ‘theoretical’ OOP concepts for ages, and never got it. Books written by people who assume the reader already understands the idea.
This article had a simple (academic!!) example that I could follow at last.
Got it, easily. More like this, please!
-Andy
-Oulu, Finland