Reputation: 5714
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");
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.
Upvotes: 9
Views: 163
Reputation: 25165
Notice that my answer focus not on the major strengths of OOP as you have already read on those and - as they currently don't apply to your situation - were meaningless. I'm going to focus on what OOP can do to you right now.
The example you give is actually a good one.
Say that you also wanted to attach height, weight, birthday and profession to a person.
Not using objects you could create an array of arrays (to store multiple persons with multiple attributes) but 2 hours into the coding you would try to access the persons job as:
echo $persons[0]['job'];
And it would fail as that field is actually named 'profession'; using objects not only will your IDE know the getters it will also help you.
The major strength of OOP is only really seen when you work in teams or expose code to be used by others however the example I gave should suffice to understand why even as a single developer there are benefits.
That being said, for over simplistic actions it can be overkill.
Upvotes: 1
Reputation: 1168
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.
Upvotes: 2
Reputation: 2915
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.
Upvotes: 2
Reputation: 48357
Consider what happens when you want to change the behaviour of the code - suppose it's been running for a while and you discover that you have lots of duplicate records where people have used variants in the whitespace and capitals. You might then want to amend the code to....
function set_name($new_name) {
$new_name=trim(strtoupper($new_name));
$new_name=str_replace(' ',' ', $new_name);
$new_name=str_replace(' ',' ', $new_name);
$name_parts=explode(' ', $new_name);
$this->surname=array_pop($name_parts);
$this->forenames=implode(' ', $name_parts);
}
function get_name()
{
return $this->forenames . ' ' . $this->surname;
}
But you don't need to change any of the code which interacts with the object.
Now think about a class which describes organizations rather than individuals - they have names - but not forenames and surnames. If you have a class with the same interface (get_name, set_name) then you can throw a mixed bundle of person and organizations at your Christmas card printer application without having to amend the app to cope with the different data types.
(tutorial examples are kept very simple for a reason, unfortunately a lot of the benefits of OO only become apparent when dealing with complex problems - stick with it and you'll get there)
Upvotes: 1