What is the pros and cons of using a page with functions instead of using an instantiated class or a static class in PHP?

#1

I’m new to OOP and I cannot wrap my head around when to use an instantiated class or a static class or a page with a few functions.

Below is my code which has a couple of functions. Should I use a static class or an instantiated class for functions similar to below?

Also, is there a performance difference in using a class versus using a page with a few functions and including them?

my-event-model.php:

function get_event_data ($event_id)
{
    $db = new Database();
    $events_data = ['event_id' => $event_id];
    $event_row = $db->select('events', $events_data);
    $event_data = [];
    foreach ($event_row as $name => $value) {
        $event_data['event_id'] = $value['event_id'];
        $event_data['event_title'] = $value['event_title'];
        $event_data['event_date'] = $value['event_date'];
    }
    return $event_data;
}

function get_event_data_info ($event_data, $calendar_date)
{
    $event_data_info = [];
    if ($event_data['event_date'] == $calendar_date)
    {
        $event_data_info['event_exists'] = 'Y';
    }
    else
    {
    	$event_data_info['event_exists'] = 'N';
    }
    return $event_data_info;
} 
#2

There is no “static class” in PHP. I think, you mean static class methods.

Answer on your question is quite easy.By big project human is not able to hold in memory whole code mit all its dependencies. That means, developer needs to create some structure with lot of independent and possibly isolated code parts. With OOP you can get it.

#3

on writing plain functions you will get into naming trouble at some point. So if you want to send an email what to do? you may want to name the function mail - oh wait, that’s already in PHP core. So you name it some_mail and run into problems when switching to a librabry. So someone else on your team brings in a class that’s called mail? No problem when you start using namespaces. And you don’t end up with something like my_mail_new_v2 and stuff. So it’s all about arranging code.

#4

Thank you very much for responding to my question.
So based on your answer, and based on the type of functions that I will be using above, would you recommend that I use a class with static methods or an instantiated class?

#5

My knowledge of classes is very limited - I have started using them extensively and what I really like is the way classes group relevant functions. A large project is easily followed and understood. Changes and modifications are easier because the functions are all compartmentalised…

…reminds me of the best selling philosophy book which I recommend all programmers to read:

#6

The thing is: you don’t just use classes, static XOR instantiated, there are several use cases for both ways, and it hardly depends on which layer of your application architecture you are working. To get a feeling for classes have a look at some PHP design patterns.

1 Like