[1+1=2]

OneAndOneIs2

« Because sometimes you need a laughBanner ads can make you happy! »

Sun, Nov 15, 2009

[Icon][Icon]Just cuz the O'Reilly examples were crap...

• Post categories: Omni, Rant, Technology, My Life, Programming, Helpful

Object-oriented programming in PHP.

As somebody whose background in languages is mostly in C, the whole OOP thing is a bit of a mystery to me. I've yet to work out why an object is better than procedural functions & structs etc., but I'm sure that'll come in time.

But I've got a few O'Reilly books laying around on the subject of PHP, so I looked to them for an answer as to what OOP really *is*

For once, they were useless. Not only because they have bugger all in the way of explanations, but also because they have such godawful code examples.

It's the names they use. One book has the same name for an object as a function, so when they refer to 'Song' you can't tell if they're calling the object or the function IN the object.

The other has the same name for two different variables. So you get this dazzlingly-clear example:

$this->str = $str;

WHICH str is which?? What IDIOT thought this was a good example??

(Actually, I can answer that one - Rasmus Lerdorf, apparently, thought having two variables with the same name would make the example easy to follow)

So I sat down and worked through the creation of an object. There's absolutely nothing useful about the code I came up with, except for the fact that if you've no idea how PHP does OOP things, this'll make things a little bit clearer. So here it is, published online just on the offchance that anyone else wants to know just how the Hell to get started with objects in PHP.

Follow up:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>PHP OOP test</title>
</head>
<body>
<?php
    // Define a new object called "object_example"
    class object_example {
        //Define an object variable
        var $object_variable = 'Object-defined variable';
        
        //Define a function that modifies the object variable
        function object_variable_rename_function($function_variable) {
            $this->object_variable = $function_variable;
        }
        
        //Define a function to echo the object variable
        function object_echo() {
            echo $this->object_variable . '<br />';
        }
    }

    //Right, having defined an object, let's make use of it!
    //Create a new instance of the object & echo its default variable
    $test_object = new object_example;
    $test_object->object_echo();

    //Use object's redefine function to change value of its variable
    $test_object->object_variable_rename_function('Function-defined variable');
    $test_object->object_echo();
    
    //Use 'extends' to create a new object that inherits from our first object
    class inheriting_object extends object_example {
        function object_variable_length() {
            echo 'The default string, <em>"' . $this->object_variable . '",</em> is ' . strlen($this->object_variable) . ' characters long.';
        }
    }
    $test_extended_object = new inheriting_object;
    $test_extended_object->object_variable_length();
?>
</body>
</html>

And the output will be (in W3C-compliant code, of course)
Object-defined variable
Function-defined variable
The default string, "Object-defined variable", is 23 characters long.

16 comments

Dion Moult
Comment from: Dion Moult [Visitor] · http://thinkmoult.com/
PHP OOP is well explained in online tutorials. Just google it up. It's mainly useful when used in a framework - try search for PHP MVC framework tutorial and perhaps you'll get a much more practical example.
15/11/09 @ 22:31
VIncent Povirk
Comment from: VIncent Povirk [Visitor] Email
You can do object-oriented programming in C, you know. It's not about the language so much as the style of programming.

You just have to make some structs. And, uh, functions that operate on the structs.
15/11/09 @ 23:06
Vincent Povirk
Comment from: Vincent Povirk [Visitor] Email
Here's what I would consider a good C example of OOP:

http://source.winehq.org/source/include/wine/list.h

The important features:
* We have an "object", a list, which represents either a doubly-linked list or an item in a doubly-linked list.
* There are a bunch of functions/macros that operate on these lists, and their names start with list_ or LIST_ so we know they're related.
* They are sufficiently generic that I could use them to make a list of anything, just as long as I make a struct with a list in it and whatever else I want a list item to contain.
* All the functions are in one place. In this case, they're declared statically, but you could also put all the function implementations in a C file and link it to your main program or library t build time.
* When using lists, you write things like list_remove(&item->list) and leave the details of how to remove a list item out of your code.

See also http://en.wikipedia.org/wiki/Object-oriented_programming#Fundamental_concepts_and_features. All of these concepts can be used in C when they are useful, and they often are.
15/11/09 @ 23:38
hari
Comment from: hari [Visitor] · http://harishankar.org/blog
I dislike OOP myself. I had bookmarked a lovely article about the problems of OOP some time ago but unfortunately my laptop is gone for servicing and I don't have that link right now with me.
16/11/09 @ 09:34
tuxdev
Comment from: tuxdev [Member]
OOP is quite nice.. when used properly and in the right situation. For example, simulations and games. Also OOP doesn't always imply dynamic binding. I often do OOP in C++ using template-based static binding.

The problem with OOP is that the Java people hyped up the term and turned it into a Silver Bullet that would solve everything. Of course it doesn't.. and it doesn't help that Java is actually a really terrible OOP system. PHP's OOP is terrible too.
16/11/09 @ 16:35
hari
Comment from: hari [Visitor] · http://harishankar.org/blog
Hi, tuxdev, I found the link to the article. I had posted it on my blog some time ago:

Here is that article:
http://www.geocities.com/tablizer/model.htm

I must say it makes a lot of sense to me.
17/11/09 @ 03:38
oneandoneis2
Comment from: oneandoneis2 [Member] · http://geekblog.oneandoneis2.org/
@Dion - actually, I've not really found anywhere that gives a good explanation of OOP. Just a bunch of pages that, after reading them long enough, you finally get the basic idea. If you know of any really good description that isn't just a mass of buzzwords, I'd love a link!

@Vincent - yeah, I know OOP is more down to how you write code than to the language. But C was never intended as an OOP language, so the books on writing it are procedural-based too: Learning C is unlikely to make you an OOP guru!

@Hari - I can see how it could be a good system in some situations, but I can't say I'm really much of a fan of it yet myself either.

@Tuxdev - what makes C++ so much better at OOP for you? (That's a question not an argument - I don't know Java or C++ at all, and I'm only starting to look at PHP's OOP..)
20/11/09 @ 12:49
tuxdev
Comment from: tuxdev [Member]
@Hari - that article isn't really fair to OOP. OOP isn't trying to model *everything*, just enough to do something useful. The examples aren't good at all, I can easily see nice OOP ways to handle those situations.

OOP only really start to shine when combined with functional or declarative programming for the actual executable bits.

@oneandoneis2 I mostly really like C++'s static typing. It's a lot easier to know what I can do with a particular object if it's nicely tagged with a type rather than everything being simply a "var". Also, the type for an argument indicates what properties or abilities the function expects from it. What kind of thing am I supposed to pass into object_variable_rename_function? Can't tell just by glancing at the prototype.
21/11/09 @ 23:34
hari
Comment from: hari [Visitor] · http://harishankar.org/blog
Hi Tuxdev. Agreed. However, the full article here is even more interesting and thorough in its criticism of OOP:

http://www.geocities.com/tablizer/oopbad.htm

I think that the author makes some excellent points to debunk common OOP myths. What I like is that he has taken nothing for granted and analyzed every aspect of OOP according to his metrics and showed why he disagrees with the alleged benefits of OOP.

While not a total convert, I must say I have never been an OOP fan in the first place and maybe that article really echoed well with my own (rather nebulous) views.
23/11/09 @ 03:52
tuxdev
Comment from: tuxdev [Member]
It's got the same problems the shorter version has. Sure, there's some valid points about OOP not being the overhyped Silver Bullet, but it's hidden in a huge amount of chaff that's just blatantly wrong.

Doing a little more research on him, he's the same "TopMind" guy that trolled the C2 wiki and got pummeled to the ground by *much* better software developers than myself.
23/11/09 @ 18:48
hari
Comment from: hari [Visitor] · http://harishankar.org/blog
But you have to admit that the cost of developing well designed OOP is much higher than the cost of developing well designed procedural programs.

In any case, I hardly begin understand the more technical aspects of the document and no doubt OOP programmers will have plenty of arguments against it.

But that's where I feel OOP fails to deliver. It's relatively easy to "get into" procedural programming. But even after a couple of years of studying OOP related programming in school, I still don't "get" it.

That's where the problem with OOP lies I feel: too much technicalities and too many details of implementation. Also the concepts can take a long time to sink in and turn into useful code from a newbie.
26/11/09 @ 03:29
tuxdev
Comment from: tuxdev [Member]
Certainly the initial cost of a procedural program is less. However, OO is really about maintenance, which is around 70% of the cost throughout an apps lifetime. Also, OO is about making more complex and useful programs. Many well-designed procedural (read: C) programs often contain quite a few OO design concepts.

You've probably never actually been taught OO in your classes. You've probably encountered "never use public member data", but that's not OO thinking, just a rule. For some stuff, like coordinates, it makes better OO sense to actually use public members.

OO thinking is a more abstract "what is a clock actually capable of *doing* and what can a clock tell you?". You can set the time, move the time forward, or read the time. That gets us a clock.setTime(), clock.tick(), and clock.toString(). Do you *really* care whether or not it's in memory as unix time-from-1970, or as year/days/hour/minute/second? Does it really make sense to have getters and setters for year/days/..? It might actually make sense to be able to extract years/days/.. individually, but that's an intentional decision, not just because you happened to store the time internally as years/days/..

Another example, from the shorter anti-OOP article, is the relationship between a mugger and the victim. Is it victim.mug(), or mugger.mug(victim)? If you think a little about who is the one actually *doing* something, the answer is obvious.

Going back to coordinates, what do they *do*? You can many of the standard mathematical operations on them, but otherwise it's just a pair or triplet of values *as defined by math, not because it's convenient*.

A lot of the technicalities in "OOP" come from being taught only the (wrong) rules, and not the real concepts.
27/11/09 @ 06:54
jzacsh
Comment from: jzacsh [Visitor] Email · http://jzacsh.com/
Hey, I'm just curious what made you look into PHP as a first for OOP (as opposed to say C++, Python, Java, blah, blah)?

Nice blog by the way :)
27/11/09 @ 09:23
oneandoneis2
Comment from: oneandoneis2 [Member] · http://geekblog.oneandoneis2.org/
@jz - I work on a variety of websites. I'm not studying PHP as a means of understanding OOP. I'm studying OOP as a means of working out what I need to do to fix the broken PHP on some web page or other :o)
27/11/09 @ 15:53
Kerberos
Comment from: Kerberos [Visitor] · http://piestar.net
OOP is a tool, just as everything else. Due to the ultimatley stateless nature of PHP it is of much less utility in it than in other languages, but the key is to learn it and realise the conditions when using it will be benificial. Even much, much worse features (like exec()) have their uses - the key is knowing when.

Inheritance, polymorphism and encapsulation are the main things OOP brings to the table. Treating it like a 'silver bullet' is a terrible idea though - overly complicated OOP code is an utter nightmare to debug and only serves to complicate things.
28/11/09 @ 22:34
justgage
Comment from: justgage [Visitor]
I enjoy OOP quite a bit, PHP's sucks honestly though. If you really want to get Object Oriented programing dabble in Ruby, it's OO to the max. Even things like strings and number are objects. Like you could do this: "john".capitalize() would yield "John" which make so much more sense then having obscure functions that belong to nothing. I'm not saying you should switch over to Ruby, I'm just saying it's concepts are enlightening when it comes to OOP.

02/01/10 @ 04:20

Leave a comment


Your email address will not be revealed on this site.

Your URL will be displayed.
(Line breaks become <br />)
(Name, email & website)
(Allow users to contact you through a message form (your email will not be revealed.)
This is a captcha-picture. It is used to prevent mass-access by robots.
Please enter the characters from the image above. (case insensitive)
 

[icon] Blogroll

[icon] Creative Hedgehog
Colmena colmena. (Quizá del celta *kolm?n?, der. de *k?lmos, paja; cf. bretón kôlôen-wénan, de kôlô, paja, y wénan, abejas). 1. f. Habitación natural de las abejas. 2. f. Enjambre que vive en la colmena. 3. f. Recipiente construido para habitáculo de las abejas. 4. f. Lugar o edificio en el que vive mucha gente apiñada. [...][Link to post]28/07/10 - SPN3730 vocabulario 2

[icon] Hari's corner
A few of my faves - please comment if you find them interesting[Link to post]24/07/10 - Photos I've taken - my favourites

[icon] Place of Stuff
Joseph&#8216;s story continues&#8230; Ten of his eleven brothers travel to Egypt to buy food to get them through the famine. Incidentally, something has occurred to me: in the tales of Joseph, God seems to be more bothered by getting Joseph into a position of power than in either preventing/alleviating the famine or in making the Israelites get [...]

[Link to post]
24/07/10 - The Bible ? Joseph is an Evil Genius

[icon] Advice From a Single Girl

So Friday (last) started out so well, I knew it was going to be an awesome day.

I slept in (ahhh, bliss) and went for a morning walk to mail some....er...mail (because, seriously, what else can you mail? turtles?) and it was sunny and warm and I hadn't had any caffeine yet so I got myself a Slurpee. Nothing says awesome Summer day like a 10 am Coke Slurpee cooling you down in the sun.

But do you know what really tipped the morning into full-blown awesomeness? The two shirtless, amazingly hot guys who jogged past me, sweaty and gorgeous as I walked home. Ahhhhh, sugar, sun, and sexy, my own personal Summer trifecta.

I went over to where C-Dawg was staying and picked her up (so there would be no driving necessary) and we came back to my apartment, poured ourselves a summer-worthy drink and headed out on the town.

We wandered through downtown, people watching and talking and laughing and window shopping and then we headed to one of the local patios and ordered up a pitcher and some appetizers.

And that's when the real fun began.

You see, C-Dawg and I love people watching. And more than that, we love making up little stories about people and trying to guess who they are. We'd soon discovered that Friday would have to be known as "Everyone Looks Familiar Day" because I kept on seeing people that I thought looked familiar but I couldn't tell if they actually were or if I was just imagining it.

We decided that the couple next to us had just boated in on their yacht and that the guys across from us were all discussing their volleyball league's last game.

We also tried to narrow down which men C felt were too young for me and which she deemed "just right." Once we'd narrowed my age-group down to a ten year span she tested me to see if I could actually tell which guys were ok and which were in the "are you crazy, he's way too young" category.

I did not do well at this. (sigh)

As the pitcher got emptied, a table behind us became filled with a bunch of guys. C-Dawg, needing to "get out of the sun" (which we're pretty sure the guys could tell was an obvious ploy for her to be able to stare at the guys instead of having to pretend to look around and can I just say thank goodness for sunglasses and how easy they make it to check out cute guys?) sat next to me and we started to figure out the back story for these guys.

Later, C decided to choose which of the guys she'd set me up with and when she did she very kindly me that I could go out with the nice, sweet, geeky one because I'm a geek too at which point I protested until she promised she was a geek as well and it wasn't a bad thing. (Strangely enough I know what she means.)

At one point, the waiter came over and there'd been this on-going joke between the three of us because servers kept on trying to bring us food we hadn't ordered and I kept on making this dumb joke about it and then when C-Dawg told me the joke was getting old and the waiter laughed, I turned to him and said (and I quote) "Hey, I'm just going to keep saying it because it never be's not funny!"

At which point he suggested that this wasn't our first patio of the evening and I couldn't stop laughing because I couldn't believe I'd said "be's" and how as I'd said it it had TOTALLY been a word.

Ahhh alcohol, what silly things you do to my brain.

We hit up a few more places after that and went for dinner at my favourite place and then watched an awesomely bad movie back at my place. (Hi, I'm Victoria and I'm going to say the word 'place' as many times as possible in one sentence. I are a good writer.)

It was pretty darn awesome and I'm sure there's more I can think of, like how she wet-willied a statue and how she almost convinced me to give nice geek guy my number and how we sat outside the best ice cream place in town and convinced a bunch of other people that yes, they really should go inside and get a cone.

A good day, a great afternoon, a fun evening. It always be's like that with the C-Dawg. I can't wait til we get to do it again.
[Link to post]
30/07/10 - It Never Be's

[icon] Nation
&#160; This was possibly the most ridiculous show I have seen in a long time and I can get Sky 1 I know ridiculous. It could be summed up in three sentences Do you know what's in your cereal? Want to? Read the label. Instead it went on for a hour about how evil the [...][Link to post]27/10/09 - Dispatches ? do you know what?s in your breakfast? (warning...

Blogroll generated by MagpieRSS

[Links][icon] My links

[Icon][Icon] Dominic just discovered that if you have two thousand mockingbirds, technically you've got two kilamockingbirds :).
30/07/10

[Icon][Icon] I last listened to:
The Offspring - She's Got Issues

[Icon][Icon] Most recent photo:
Submersible houseboat

[Icon][Icon]About Me

[Icon][Icon]About this blog

[Icon][Icon]My LQ profile

[Icon][Icon]My /. profile

[Icon][Icon]My Wishlist

[Icon]MyCommerce

[FSF Associate Member]


July 2010
Mon Tue Wed Thu Fri Sat Sun
 << <   > >>
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31  

Search

User tools

XML Feeds

eXTReMe Tracker

Valid XHTML 1.0 Transitional

Valid CSS!

[Valid RSS feed]

powered by b2evolution free blog software