By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
432,035 Members | 1,543 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 432,035 IT Pros & Developers. It's quick & easy.

Classes vs functions

P: n/a
I've been using functions since I first started using php, but I've been
hearing more and more about classes, which I never really looked at that
much. I understand the whole OO programming aspect, but are there any
advantages to having classes as opposed to just functions? I've heard that
the classes are better because they only load the functions they need to,
where with an include file of functions, the whole page gets loaded, even
if you only use a couple functions on a certain page. I've searched around
and can't find any "official" mention of this though. So, is that true and
should I start migrating to using classes instead of functions?

--
VR
Jul 17 '05 #1
Share this Question
Share on Google+
18 Replies


P: n/a
vrillusions:
I've been using functions since I first started using php, but I've been
hearing more and more about classes, which I never really looked at that
much. I understand the whole OO programming aspect, but are there any
advantages to having classes as opposed to just functions? I've heard
that the classes are better because they only load the functions they need
to, where with an include file of functions, the whole page gets loaded,
even
if you only use a couple functions on a certain page. I've searched
around
and can't find any "official" mention of this though. So, is that true
and should I start migrating to using classes instead of functions?


No. That sounds rather confused to me. PHP obviously isn't omniscient and
thus has to parse all the source files it reads in.

André Nęss
Jul 17 '05 #2

P: n/a
On 2003-12-11, vrillusions <vrillusions@not_this.neo.rr.com.invalid> wrote:
I've been using functions since I first started using php, but I've been
hearing more and more about classes, which I never really looked at that
much. I understand the whole OO programming aspect, but are there any
advantages to having classes as opposed to just functions?

If you do understand OOP, you should see the _possible_ advantages if used
right... (But if you see them, why did you choose for PHP anyway?
Doesn't J2EE seem more appropriate?)
I've heard that
the classes are better because they only load the functions they need to,
where with an include file of functions, the whole page gets loaded, even
if you only use a couple functions on a certain page. I've searched around
and can't find any "official" mention of this though. So, is that true and
should I start migrating to using classes instead of functions?


One could make a really big class with all functions in it. This would
be as dumb as not making groups of functions, in separate files.

--
verum ipsum factum
Jul 17 '05 #3

P: n/a
vrillusions wrote:
I've been using functions since I first started using php, but I've been
hearing more and more about classes, which I never really looked at that
much. I understand the whole OO programming aspect, but are there any
advantages to having classes as opposed to just functions?
I think so... But in PHP, you can probably do the same thing without OO.

What I personnaly like w/ OO (in general) is that it allows to have
different substitutable implementations of a same concept, with a
uniform representation.

Note that you clearly don't need classes to have ADTs in PHP, but this
won't give you polymorphism (or not as easily). Now whether you need
this or not depends on your application and coding style. Having mostly
used (more or less) OO languages since I began programming, I'm may be a
bit biased !-)

Another point that is more PHP-specific is that PHP not having any
module concept, classes can also be used to emulate modules, thus
uncluttering the global namespace.
I've heard that
the classes are better because they only load the functions they need to,
where with an include file of functions, the whole page gets loaded, even
if you only use a couple functions on a certain page. I've searched around
and can't find any "official" mention of this though. So, is that true
I've never heard of such a thing, and really doubt it's even possible in
PHP.
and
should I start migrating to using classes instead of functions?


That's another problem, and this one is up to you... But you probably
shouldn't care if you don't have a need for it.

My 2 <euro>cents,
Bruno

Jul 17 '05 #4

P: n/a
>(But if you see them, why did you choose for PHP anyway?
Doesn't J2EE seem more appropriate?)


Certainly not! Java's strong typing in combination with it's primitive
datatypes is a pain in the ass. So is it's obligation to either handle
exceptions or declare to be throwing them. It is allso a matter of
mentality: Java's developers tend to make everything unnecessary
complicated. For example this absurd idea of EJB (Enterprise Java Beans, a
part of J2EE) that everything is distributed. This means that looping
through a thousend objects and retrieving a value form each will require a
thousend remote method invocations (these are at least a hundred times
slower then local method calls, but if these objects happen to reside on the
other end of the world each method call takes half a second or more). (in
the end they had te reintroduce
local objects kind of through a back door).

The more generic (= reusable) your code gets, the more you
run into the inflexibilities and bad designs of Java. I'm not alone here,
look at the Lightwieght Languages workshop (http://ll1.ai.mit.edu/) and its
discussion archive
(http://www.ai.mit.edu/~gregs/ll1-dis...l/threads.html - takes
a few minutes to download)

But let's talk about the advantages of OO. It comes down to:
- delegation + polymorphism
- encapsulation
- inheritance

Delegation means that you want something done but you do not do it yourself
but have an object do it for you. This is done by using a service, wich is
dispatched tp a function on an object. Now what is the difference between
calling a normal function and using a service? Polymorphism! The class of
which the object is intstantiated is decisive for which function is actually
executed. For example if i am building an ecommerce website i could have a
class "DeliveryService" with a subclass "ExpessDelivery" and another
subclass "Standard Delivery". Somehwere in the order intake i ask the
customer to select a delivery service. On the basis of his selection i
instantiate the corresponding class and tell the object te delivery adress.
Then i can ask the object for the dilivery price and maybe how long the
delivery will take. If the object is an instance of ExpessDelivery it will
ececute the functions of ExpessDelivery to calculate the price, which will
probably be higher then for a StandardDelivery.

So far you could reach the same result with some case swithches in normal
functions. But here comes the trick: When the owner of the ecommerce website
asks me to add another delivery service, let's say "Collect On Delivery",
where his customer can pay on delivery to the guy that delivers the order, i
can simply add another class CollectOnDelivery and implement it's functions.
With case swithches i would have to add a case to each case switch. In order
to do that i would first have to find all these case switches hidden in
whatever function where i have (or worse, someone else has) once written
them. This makes well-designed OO software more flexible and easier to
maintain.

You can see it like this: in OOP we put our functions into a large
multilayered
case switch, called the class hierarchy, while in conventional
programming you have to replicate many case switches throughout you code.
So, if you have little case switches (including if-elseif-etc) you will
probably not
need OOP. If your case switches are becoming a headache you should obviously
have used OO right from the start.

OK, this is more then enough, i suggest someone else explains encapsualtion
and
inheritance and their advantages.

Greetings,

Henk Verhoeven,
www.metaclass.nl

Jul 17 '05 #5

P: n/a
With total disregard for any kind of safety measures vrillusions
<vrillusions@not_this.neo.rr.com.invalid> leapt forth and uttered:
I've been using functions since I first started using php, but
I've been hearing more and more about classes, which I never
really looked at that much. I understand the whole OO
programming aspect, but are there any advantages to having
classes as opposed to just functions? I've heard that the
classes are better because they only load the functions they
need to, where with an include file of functions, the whole page
gets loaded, even if you only use a couple functions on a
certain page. I've searched around and can't find any
"official" mention of this though. So, is that true and should
I start migrating to using classes instead of functions?


I usually point people towards this post at Sitepoint whenever
this question is raised: http://sitepointforums.com/showpost....8&postcount=14

Happy reading. :-)

--
There is no signature.....
Jul 17 '05 #6

P: n/a
On 2003-12-11, Henk Verhoeven <ne**@metaclassREMOVE-THIS.nl> wrote:
(But if you see them, why did you choose for PHP anyway?
Doesn't J2EE seem more appropriate?)


[long snipped on advantages of OOP]

I agree that OOP has it's advantages...

But my point was: If the OP really wanted to make use of these advantages,
why did he choose for PHP in the first place? (Assuming his project is
is not using OOP, as PHP never had really support for OOP).

--
verum ipsum factum
Jul 17 '05 #7

P: n/a
Tim Van Wassenhove wrote:
On 2003-12-11, Henk Verhoeven <ne**@metaclassREMOVE-THIS.nl> wrote:
(But if you see them, why did you choose for PHP anyway?
Doesn't J2EE seem more appropriate?)


[long snipped on advantages of OOP]

I agree that OOP has it's advantages...

But my point was: If the OP really wanted to make use of these advantages,
why did he choose for PHP in the first place?


<troll>
Because Java sucks ?
</troll>
(Assuming his project is
is not using OOP, as PHP never had really support for OOP).


Too big. Won't work.

Jul 17 '05 #8

P: n/a
Tim,
PHP never had really support for OOP


How do you mean? What OOP support do you miss in, let's say php4 ?

Greetings,

Henk Verhoeven.

Jul 17 '05 #9

P: n/a
On 2003-12-12, Henk Verhoeven <ne**@metaclassREMOVE-THIS.nl> wrote:
Tim,
PHP never had really support for OOP


How do you mean? What OOP support do you miss in, let's say php4 ?


A way to "hide" data in a class, never found a way to declare a
variable/method as private.

--
verum ipsum factum
Jul 17 '05 #10

P: n/a
With total disregard for any kind of safety measures Tim Van
Wassenhove <eu**@pi.be> leapt forth and uttered:
On 2003-12-12, Henk Verhoeven <ne**@metaclassREMOVE-THIS.nl>
wrote:
Tim,
PHP never had really support for OOP


How do you mean? What OOP support do you miss in, let's say
php4 ?


A way to "hide" data in a class, never found a way to declare a
variable/method as private.


How has this inability ever prevented an application from working?

I describe an important lack as something that actively stands in
the way of an application being developed. Hardly the case with
private/protected methods...

--
There is no signature.....
Jul 17 '05 #11

P: n/a
Tim Van Wassenhove wrote:
A way to "hide" data in a class, never found a way to declare a
variable/method as private.


Prepend an underscore before the variable/method name and use some
discipline and common sense to treat that as private. Worked for me
every time...

Jochen

Jul 17 '05 #12

P: n/a
Phil Roberts wrote on Friday 12 December 2003 16:02:
How do you mean? What OOP support do you miss in, let's say
php4 ?


A way to "hide" data in a class, never found a way to declare a
variable/method as private.


How has this inability ever prevented an application from working?

I describe an important lack as something that actively stands in
the way of an application being developed. Hardly the case with
private/protected methods...


That's easy for PHP4. I can list some off the top of my head:

- interfaces and/or multiple inheritance;
- packages;
- ability to destroy objects (and free associated memory);
- abstract classes.

I'm sure there are few others as well. PHP5 takes care of good deal of this
type of OO functionality but you asked about PHP4 ;)

--
Business Web Solutions
ActiveLink, LLC
www.active-link.com/intranet/
Jul 17 '05 #13

P: n/a
Phil,

I agree with Tim that there is more to building applications then getting
them to work. For example modularization does make large applications easier
to maintain, and is even more important when you use third party components.
But i do not like his solution: private fields & functions (assuming he uses
it in the C++/Java meaning) because:
- a class is too small as a module. It is good desing to make objects
cooprerate closely. It is logical to see those objects together as a module,
and it may help maintenance to declare some parts of the module as only to
be called from inside the module.
- the polymorphism often requires that methods are overridden in subclasses.
If the field or method called by the overridden method are private it can be
hard or impossible to build the overriding method. So if i where to choose
between having "private" or "protected" added to php, i would certainly
choose "protected".
- persistency frameworks need access to fields. If they are private or
protected there must be a workaround, otherwise, like in java, one will have
to make all persistent fields public. The only language i know of that has
such a workaround is Smalltalk, where all fields are protected.

Smalltalk has an interesting concept of private methods: Nothing stops you
from calling them, but with the default settings of the IDE they are
invisible unless you explicitely choose to see them. Becuase the
"priviteness" of methods is not enforced, one can give "private" one's own
meaning. In the Smalltalk class library however, it means that such a method
is not part of the api, so if you call it you do so on your own risk: no
effort is made that the same method will be present in next release.
Effectively this kind of private is very large scale: the entire Smalltalk
class library is one method and "private" defines what should not be used
from outside the module.

In fact there is little that stops one from defining one's own meaning of
"private" and put comments accordingly ito his code, but i must admit, this
will not be half as effective without a development environment that
supports it.

Greetings,

Henk Verhoeven,
www.metaclass.nl
"Phil Roberts" <ph*****@HOLYflatnetSHIT.net> wrote in message
news:Xn***********************@206.127.4.22...
With total disregard for any kind of safety measures Tim Van
Wassenhove <eu**@pi.be> leapt forth and uttered:
On 2003-12-12, Henk Verhoeven <ne**@metaclassREMOVE-THIS.nl>
wrote:
Tim,

PHP never had really support for OOP

How do you mean? What OOP support do you miss in, let's say
php4 ?


A way to "hide" data in a class, never found a way to declare a
variable/method as private.


How has this inability ever prevented an application from working?

I describe an important lack as something that actively stands in
the way of an application being developed. Hardly the case with
private/protected methods...

--
There is no signature.....

Jul 17 '05 #14

P: n/a
> - interfaces
How would a "real" interface differ from a class that is clearly
recognizable as an interface and a comment in every class that "implements"
the interface that it does so? IOW, what's an interface without strong
typing?

What i missed in Java was the ability to use a class as an interface. I
mean: the ability to declare that my class implements all public methods
defined by an other class. There is no reason why that would not run so i
think the compiler should compile it.
and/or multiple inheritance; Would'nt multiple inheritance be a little over the top for "the basic of the
internet"?
- packages; It is already possible (and advisable) to put classes together into a
package-like directory. I agree it would be nice (but more
resource-consuming) to be able to include an entire package. But is is
entirely possible to write a function that does so. For some reason i never
needed it enough to write it...

Most interesting is the namespaceing effect of packages in Java, making
abbreviated class names unique outside their package if they are unique
inside. If you follow PEAR's class name convention you have the same effect,
but miss the ability to 'leave out" the package name if you have imported
the package. The result is a lot of extra typing and harder to read code.
Personally i prefer to have the same prefix for all classes of the same app,
and one other prefix for all classes of our reusable framework.
- ability to destroy objects (and free associated memory); Interesting, did you ever run into memory limitations within a single http
request? I would rather like to have a way NOT to have objects destroyed at
the end of a http request (i do not count serialization in the session as
very usefull in this respect). But i admit that this would cause all kinds
of multi-user-multi-threading problems if you do not adhere quite strictly
to a thread safe programming style, so it would make programming php so much
more complex that most apps should not use it.
- abstract classes. What's wrong with an @abstract comment? Why would anyone want to instantiate
an abstract class if it is clearly incomplete? And why NOT instantiate an
"abstract" class if it's clearly complete for the function it going to be is
used for?

I'm sure there are few others as well. PHP5 takes care of good deal of this type of OO functionality but you asked about PHP4 ;)
Does php 5 add all this? I did not notice (my fault). I like php 4 very much
because of it's simplicity (remember the eXtreme Programming motto: the
simpelest thing that could possibly work?). But php4 has very irritating
limitations for OOP, which surpisingly no-one here mentioned:
- the habit op php4 to recursively copy anything that is not passed by
reference. This got even worse when passing by reference by the caller
started to cause warnings. It renders functions like array_slice virtually
useless with (potentially) large arrays of objects
- references to variables instead of references to objects. (It took me a
while to find the workaround: create a temporary variable in a function, put
an object into it, then have the funcion return a refernce to the temporary
variable. As no one else can have a reference to the temporary variable
unless you pass them one, it pritty much behaves like a referene to the
object itself).
- no stack trace and no try-catch for exception handling. If you heavily
reuse code and that code triggers an error you end up with a useless line
nuber of the trigger_error in the generic code, left guessing which one of
the many places from which the reused code was called caused the error.
All of these are solved by PHP5. I really look forward to it, but as we use
low cost hosting providers (one still runs php4.1) it may take a while
before it becomes mainstream...

Greetings,

Henk Verhoeven,
www.metaclass.nl.

"Zurab Davitiani" <ag*@mindless.com> wrote in message
news:JH*******************@newssvr25.news.prodigy. com... Phil Roberts wrote on Friday 12 December 2003 16:02:
How do you mean? What OOP support do you miss in, let's say
php4 ?

A way to "hide" data in a class, never found a way to declare a
variable/method as private.

How has this inability ever prevented an application from working?

I describe an important lack as something that actively stands in
the way of an application being developed. Hardly the case with
private/protected methods...


That's easy for PHP4. I can list some off the top of my head:

- interfaces and/or multiple inheritance;
- packages;
- ability to destroy objects (and free associated memory);
- abstract classes.

I'm sure there are few others as well. PHP5 takes care of good deal of

this type of OO functionality but you asked about PHP4 ;)

--
Business Web Solutions
ActiveLink, LLC
www.active-link.com/intranet/


Jul 17 '05 #15

P: n/a
With total disregard for any kind of safety measures "Henk
Verhoeven" <ne**@metaclassREMOVE-THIS.nl> leapt forth and uttered:
- no stack trace and no try-catch for exception
handling. If you heavily reuse code and that code triggers an
error you end up with a useless line nuber of the trigger_error
in the generic code, left guessing which one of the many places
from which the reused code was called caused the error.


There is the debug_backtrace() function. But it doesn't really
compare with proper exception handlers I'll agree.

--
There is no signature.....
Jul 17 '05 #16

P: n/a
Henk Verhoeven wrote:
- interfaces How would a "real" interface differ from a class that is clearly
recognizable as an interface and a comment in every class that
"implements" the interface that it does so? IOW, what's an interface
without strong typing?


Interfaces were Java's "solution" to multiple inheritance. They are useful
in a way that one class may implement one or more interface.
and/or multiple inheritance;

Would'nt multiple inheritance be a little over the top for "the basic of
the internet"?


I don't think multiple inheritance would have been over the top at all for
PHP; nobody would be obligated to use or abuse it. PHP is slowly but surely
expanding beyond web uses like non-web scripting and GUI. Last I checked
PHP5 will provide interfaces which is adequate.
- packages;

It is already possible (and advisable) to put classes together into a
package-like directory. I agree it would be nice (but more
resource-consuming) to be able to include an entire package. But is is
entirely possible to write a function that does so. For some reason i
never needed it enough to write it...


PHP has no concept of packages at all. What you implement is yours and yours
alone, and nobody is obligated to follow your way.
Most interesting is the namespaceing effect of packages in Java, making
abbreviated class names unique outside their package if they are unique
inside. If you follow PEAR's class name convention you have the same
effect, but miss the ability to 'leave out" the package name if you have
imported the package. The result is a lot of extra typing and harder to
read code. Personally i prefer to have the same prefix for all classes of
the same app, and one other prefix for all classes of our reusable
framework.
I devised my own way of importing classes and called it ActiveLink IORCA
(it's actually one simple function):
http://www.active-link.com/intranet/software.php
The use is similar to Java's imports. I think it would be beneficial if PHP
provided one simple way of doing this within the environment so that all
packages would be used in a consistent manner; but then again, there's
downsides to this too, so it's a topic for some discussion. I was simply
pointing out that the feature wasn't there.

Related to this, you may want to check out autoload in PHP5, I think that's
a nice new feature for loading only the classes that will be used.
- ability to destroy objects (and free associated memory);

Interesting, did you ever run into memory limitations within a single http
request?


Yes, when doing benchmarking. Also, when using PHP for non-web scripting.
I would rather like to have a way NOT to have objects destroyed
at the end of a http request (i do not count serialization in the session
as very usefull in this respect). But i admit that this would cause all
kinds of multi-user-multi-threading problems if you do not adhere quite
strictly to a thread safe programming style, so it would make programming
php so much more complex that most apps should not use it.
I guess theoretically, it's possible to come up with a persistent storage
mechanism that will keep PHP objects in their state, and I'm not referring
to serialization either. But I don't know how practical that is at all. My
guess is that it's not very practical.
- abstract classes.

What's wrong with an @abstract comment? Why would anyone want to
instantiate an abstract class if it is clearly incomplete? And why NOT
instantiate an "abstract" class if it's clearly complete for the function
it going to be is used for?


I don't know if I can explain better than many others already have. Try
this:
http://java.sun.com/docs/books/tutor.../abstract.html
I'm not arguing that abstract classes are a "must-have" in PHP4, but they
are useful in certain situations. Again, last I checked, PHP5 will allow
for abstract classes.
I'm sure there are few others as well. PHP5 takes care of good deal of

this
type of OO functionality but you asked about PHP4 ;)


Does php 5 add all this? I did not notice (my fault). I like php 4 very
much because of it's simplicity (remember the eXtreme Programming motto:
the simpelest thing that could possibly work?). But php4 has very
irritating limitations for OOP, which surpisingly no-one here mentioned:
- the habit op php4 to recursively copy anything that is not passed by
reference. This got even worse when passing by reference by the caller
started to cause warnings. It renders functions like array_slice virtually
useless with (potentially) large arrays of objects


This is not a strictly OOP-related phenomenon. That's the way PHP4 works
with all variable types.
- references to variables instead of references to objects. (It took me a
while to find the workaround: create a temporary variable in a function,
put an object into it, then have the funcion return a refernce to the
temporary variable. As no one else can have a reference to the temporary
variable unless you pass them one, it pritty much behaves like a referene
to the object itself).
I think it's too late for me, but I tried reading this over and over but I
still don't get completely what you were trying to do and what you ended up
doing. Sorry.
- no stack trace and no try-catch for exception handling. If you heavily
reuse code and that code triggers an error you end up with a useless line
nuber of the trigger_error in the generic code, left guessing which one of
the many places from which the reused code was called caused the error.


You are right, but again, this is not an OOP-related issue. You could end up
in the same boat by only [re]using functions and libraries thereof.
Jul 17 '05 #17

P: n/a
"Zurab Davitiani" <ag*@mindless.com> wrote in message
news:DS*******************@newssvr29.news.prodigy. com...
(..)
The use is similar to Java's imports. I think it would be beneficial if PHP provided one simple way of doing this (...) I agree, i just would not have a classloader called "packages".
(..) Related to this, you may want to check out autoload in PHP5, I think that's a nice new feature for loading only the classes that will be used.
Interesting, i'll do that, thanks!
(..) I guess theoretically, it's possible to come up with a persistent storage
mechanism that will keep PHP objects in their state, and I'm not referring
to serialization either. But I don't know how practical that is at all. My
guess is that it's not very practical.
I have a persistent storage mechanism that stores objects in MySql and
retrieves them,
i do think that is practical for OOP, but that is not what i mean.
I do cache objects once loaded, but that cache never
survives the end of a request. In java and Smalltalk i could cache as long
as i wanted to,
reusing the same objects for many requests without the overhead
of memory allocation and database retrieval...

(.. references to returned temps) I think it's too late for me(..)
I do not really understand the implications either, the php documentation is
not clear about what happens with chains of references, i can only test
and try to induce. (According to the incredibly odd bugs i ran into,
the php engine sometimes looses track too :-( ). But i can work around it
and i suppose this problem will go away in php5, so i do not want to
distract
the engine developers with these rare anomalies.

(.. passing by value, no exceptions catch ...) You are right, but again, this is not an OOP-related issue. You could end up in the same boat by only [re]using functions and libraries thereof.

You are right, the relation with OOP is indirect.

Greetings, thanks to all for the interesting discussion,

Henk Verhoeven,
www.metaclass.nl.

Jul 17 '05 #18

P: n/a
Hi...

Zurab Davitiani wrote:
That's easy for PHP4. I can list some off the top of my head:

- interfaces and/or multiple inheritance;
- packages;
- ability to destroy objects (and free associated memory);
- abstract classes.
I've never found any of these to be a fundamental limitation. Lack of
destructors causes painful workarounds, but script execution is a short
process.

The thing that really hurts is lack of exceptions. Namespaces would be
really useful too.
I'm sure there are few others as well. PHP5 takes care of good deal of this
type of OO functionality but you asked about PHP4 ;)


I don't know why they added a "final" keyword. Also they have been
greedy with the (only) namespace. "Iterator" could become a reserved
word :(. PHP6?

yous, Marcus
--
Marcus Baker, ma****@lastcraft.com, no***@appo.demon.co.uk

Jul 17 '05 #19

This discussion thread is closed

Replies have been disabled for this discussion.