Re: Speaking of OOP
| From: | Ignacio Vazquez-Abrams | Date: | Tue, 09 Jan 2001 22:34:31 +0000 |
| Subject: | Re: Speaking of OOP | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-33568@lists.php.net to get a copy of this message | ||
On Tue, 9 Jan 2001, John Guynn wrote:
> I am a hardware guy hacking my way through building dynamic web pages using
> PHP and MySQL and I just can't get the concept of OOP. I don't understand
> what a class can offer that I can't do with a function. I've tried to read
> a couple of books about OOP and a chapter about classes and such in a PHP
> book and I just can't grasp the concept.
>
> Can someone explain to me how a class makes my life easier compared to using
> functions.
>
> Thanks in advance,
>
> John Guynn
>
> This email brought to you by RFCs 821 and 1225.
>
You are absolutely right. There is not one single thing that can be done with
classes that couldn't be done with functions. Not in PHP anyway. The main use
of OOP is the abstraction of data along with the code used to manipulate it.
Observe:
<?php
$circle=Array();
$circle["radius"]=5;
$square=Array();
$square["width"]=4;
$square["length"]=3;
function area1($w, $h)
{
return $w*$h;
};
function area2($shape)
{
return $shape["width"]*$shape["height"];
};
$squarearea=area1($square["width"], $square["height"]);
$badarea=area1($square["height"], $circle["radius"]);
$squarearea=area2($square);
$badarea=area2($circle);
?>
Now using OOP:
<?php
class Circle
{
var $radius;
function Circle($r=0)
{
$this->redius=$r;
}
function area()
{
return $this->radius*$this->radius*3.1415;
}
};
class Square
{
var $width;
var $height;
function Square($w=0, $h=0)
{
$this->width=$w;
$this->height=$h;
}
function area()
{
return $this->width*$this->height;
}
};
$circle=New Circle(5);
$square=New Square(4, 3);
$circlearea=$circle->area();
$squarearea=$square->area();
?>
In short, OOP makes it just slightly more difficult to screw things up. PHP's
OOP model is missing two things (field scope [private, protected, public] and
class destructors) that prevent it from being as powerful as it could be, but
it beats flipping switches :)
--
Ignacio Vazquez-Abrams <ignacio@openservices.net>