Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new to oop in PHP a plea for clarifying concepts

Tags:

oop

php

I love the PHP language, Ive got SOME coding experience but I am fairly new to PHP although I have been learning a lot I feel I am now stuck / held back by not getting the hang of OOP concepts, although I have been browsing through multiple tutorials.

This is not so much a question about the code itself but rather behind the logic of it

Consider this tutorial I worked from

class person { 
    var $name; 
    function set_name($new_name) { 
        $this->name = $new_name;
    } 
    function get_name() { 
        return $this->name 
    } 
} 

$stefan = new person();
$jimmy = new person;   
$stefan->set_name("Stefan Mischook"); 
$jimmy->set_name("Nick Waddles");  

echo "Stefan's full name: " . $stefan->get_name(); 
echo "Nick's full name: " . $jimmy->get_name(); ?> 

I understand what is going on above and I understand the concept but I cant see the benefit of it, I just feel I could have created the above in a much simpler way by simply doing

function person($name){
    return $name;
}
echo person("Tim Jones");
  • Why the getter and the setter function, why not just one function in class person?
  • Why go through all that code above when my function above is so much shorter?
  • Where is the benefit here?

I'm basically just looking for someone to give me a bit of clarification on the whole OOP concept which I cant seem to get by the many repetitive tutorials I have been reading.

like image 600
Timothy Coetzee Avatar asked Jul 29 '15 15:07

Timothy Coetzee


People also ask

What are the Oops concepts in PHP?

Major OOPS Concepts in PHP PHP is an object-oriented programming language that supports several concepts. Some of them are as follows: Class and objects– Class is a programmer-defined data type, including local variables and local methods. It is also a collection of objects, while objects have similar properties and behaviours.

What are the object-oriented programming principles in PHP?

The major object-oriented programming principles in PHP are as follows: Encapsulation- This concept highlights the binding properties, methods, and hides implementation details. The prime objective of encapsulation is to limit the complications during software development, and it also simplifies using class objects.

What are the advantages of OOP in PHP?

OOP is faster and easier to execute OOP provides a clear structure for the programs OOP helps to keep the PHP code DRY "Don't Repeat Yourself", and makes the code easier to maintain, modify and debug OOP makes it possible to create full reusable applications with less code and shorter development time

What is object-oriented programming (OOP)?

OOP is programmed in such a way that the users can focus on the object while developing the program and code, but not the procedure. OOP also focuses on drawing programming close to real life. In this article, we will be exploring some of the core OOP concepts in PHP. PHP is an object-oriented programming language that supports several concepts.


2 Answers

A good case for using classes is when you may want to expand or rewrite functionality later on.

A few years back I wrote an application in PHP which was used to create issues within Jira. At this point, I was using SOAP to perform the actual issue creation and updates using the published API

Later on, within the same application, I needed to use features within Jira which were associated with the Atlassian Greenhopper/Agile extension. This extension used a REST API and it became apparent that Atlassian was moving all their APIs across to using REST

As I had used a class for the calls to Jira, all the actual grunt work in the background was abstracted. I knew which data was expected and what data I would be expecting

In the end, I wrote a new class to use REST (via cURL calls), and re-wrote the class which accessed Jira. I didn't have to go through the whole application and check each call to a Jira function as the data in and data out was the same.

In reality, the classes I wrote all descended from the REST class:

  • REST -> JIRA_BASE -> JIRA

The JIRA_BASE class contained methods which were common across all Jira projects (get project names, get user id's etc). The JIRA class itself contained a couple of functions (createJiraIssue and updateJiraIssue) which were particular to each Jira project

The other advantage of using classes and objects is that you can put place-holders in for functions. In the REST class, trying to use a DELETE method (rather than GET, POST or PUT) for a REST call would error straight away (I hadn't written it as I didn't need it). However, I have re-used the same class in another application where I did need to use the DELETE method so that is now written

It also became apparent that the new application needed a change in one aspect of functionality. This was implemented without re-writing any of the calling code

Getters and setters are used to ensure that data is accessed in a controlled manner. If you just use a variable within a script, any part of that script could alter the data. If that data is stored within a class and set to private, then only a call to the getter or setter can alter or retrieve that data.

Additionally, getters and setters can alter the way the data is actually stored but still present it in a usable format. For example, when performing a call to

$obj -> setName('DaveyBoy');

that data could be reversed, escaped, encrypted, stored in session variables, sent to a database and rot13'ed (in no particular order). But, a call to

$name  = $obj -> getName()

would still store 'DaveyBoy' in $name without any intervening steps.

I've rambled about classes and why I use them but, hopefuly, this helps to explain a bit.

like image 197
DaveyBoy Avatar answered Oct 23 '22 10:10

DaveyBoy


The advantages of OOP is that anything acting upon a class or object does not need to know how that class or object works under the hood, and much more complicated things can be accomplished in the background with the bulk of your application being un-involved, making your code much more readable.

Consider the following [partially]pseudocode web app example:

$users = array();
$users[] = new User('joe', ADMIN, ACTIVE);
$users[] = new User('jane', ADMIN, ACTIVE);
$users[] = new User('bill', USER, INACTIVE);

class User {

    public $Name;
    public $Security;
    public $Active;

    public function __construct($name, $security = USER, $active = INACTIVE) {
        $this->Name = $name;
        $this->Security = $security;
        $this->Active = $active;
    }

    public function ToggleActive() {
        //Not actual working code ahead
        $this->Active = ($this->Active) ? INACTIVE : ACTIVE;
        $sql->query('UPDATE users SET active=$this->Active WHERE name=$this->Name');
    }

    public function SetSecurity($security) {
        //More non-functional examples
        $this->Security = $security;
        $sql->query('UPDATE users SET security=$this->Security WHERE name=$this->Name');
    }

}

?>

<html>
    <form>
        <!-- this is, of course, the wrong markup, but the concept is there-->
        foreach($users as $user) {
            <name>$user->Name</name>
            <security>$user->Security <button $user->SetSecurity(ADMIN)>Set Admin</button> <button $user->SetSecurity(User)>Set User</button>
            <active>$user->Active <button $user->ToggleActive>Toggle Active</button>
        }
        <!-- you could even have the class itself output the form html with something like $user->DrawEntryHTML();-->
    </form>
</html>

Obviously, there is a lot more that goes in to the web app interface of such an operation (AJAX, function handlers, etc.), but the basics are there, and only the user object itself needs to know how to perform the operation. The rest of your app can simply say Hey, user. You're active now.

OOP gives you an abstract but meaningful way of accomplishing what you want your application components to do. In most applications these days, when a user interacts, or a task happens, a number of things need to happen in order to store, display, and modify its elements. You also gain the advantage of only needing to change a small bit of code in your class in case of a change, update, or feature addition, rather than chasing all over the rest of your code for everything that relates to your users (in this case).

You'll find that a well-written OOP application has a very short program loop (or index.php), and the bulk of the work happens within its class objects.

like image 36
SuperJer Avatar answered Oct 23 '22 11:10

SuperJer