Forum Moderators: coopster

Message Too Old, No Replies

Why should I use a class?

         

csdude55

4:09 am on Aug 12, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm self taught and have been coding for darn near 25 years, but I can't say that I've ever intentionally written a class. But since I'm playing and always trying to learn, I'd like to know what the big advantage is.

For example, this is close to the example given on php.net:

class thisClass {
function thisFunc() {
return 'bar';
}
}

$foo = new thisClass;
echo $foo->thisFunc();


What is the advantage to that as opposed to:

function thisFunc() {
return 'bar';
}

echo thisFunc();


I recognize, of course, that the example is super simple and there might not be a specific advantage in that case. But I've been reading about it all day, and the only real reason I can find to use a class is because "it makes the code clearer". It definitely doesn't seem clearer to me, though, so is it just something that a different type of programmer would think is clearer?

httpwebwitch

7:13 pm on Aug 23, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Yes it's a nice way to organize your code. That is the big one.

Using classes you also benefit from all the power of OOP. You can extend and inherit, override, create methods that are private / protected / public, and there are dozens of great code "design patterns" you'll benefit from, because for every tricky problem you'll encounter there's probably someone who already solved it in some generic way. Builders, Factories, Singletons, Prototypes, Adapters, Bridges, Decorators... they're all part of a programmer's arsenal of "I already know how to do that".

What I'd consider to be the greatest advantage of using classes, is you'll be able to work with other PHP programmers and they won't look at your code and go "eewwww"