Hack Forums
[PHP] An Introduction to OOP (Object-Oriented-Programming) In PHP - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Web Development (https://hackforums.net/forumdisplay.php?fid=183)
+---- Thread: [PHP] An Introduction to OOP (Object-Oriented-Programming) In PHP (/showthread.php?tid=3045954)

Pages: Pages 1 2 3


An Introduction to OOP (Object-Oriented-Programming) In PHP - GaBaNo - Nov 24, 2012

Let me explain, before I start, that this might be a little off. It's mostly community and feedback created, so yeah. I don't use OOP a lot, and am kind of new to it. The original tutorial was shit, but I've added a lot to it from feedback and articles. Credits are listed at the bottom of the page.

OOP is mainly used for variable reusage and, as many people say, relates to real life situations so it's easier to understand.

PHP is a multiple-paradigm language, meaning you can write it in either procedural or object orientated. The language itself is not fully object orientated, and you cannot make it so.

So, in OOP, we usually have two files: the class, and then the handler. Let's get started with our class:

class.php
PHP Code

<?php
class OOP {
public 
$variable;
}
?>

As you can see, the class name does not have to be the same as the file name (but it is highly recommended to be so), like how it is in java and many other programming languages. Also, notice how we defined our variable as a public status. This is because if you do not put anything before the variable, it gives you an error. Please note that there are a bunch of things you can put in front of your variable - it all really depends to be honest. They are called modifiers and modify how the variable is used. For some of the modifiers, please look at the bottom of the page. You may have also noticed that our variable is undefined. It can be defined or kept this way, it does not matter.

Now, we need to define our variables. Well, if we did not define them straight away, then how do we do this? It's simple, and here's how:

PHP Code

<?php
class OOP {
public 
$variable;

function 
__construct() {
$this->variable = "Hello";
}

}
?>

As you can see, we defined it using the $this-> method. Now, let me explain what $this-> means:

In any programming language, "this" references to the class you are working in. If you attempt to do a "this" in a regular PHP file with no class, you will get an error as there is no object/class to reference the variable to. Also, we defined it in a function and not just out in the open. Why? Because we would have gotten a syntax error (explained below).

* QUICK STOP NOTE *
  • Syntax Error: You would have received the "EXPECTING T_FUNCTION" error when using any function besides your own in a class
  • public function __contruct {} - This is a constructor (listed at the bottom of the page). A constructor is called whenever a object initializes as a result from a class.

Now that we have defined our variable, how would we display it on the page? Well, we certainly wouldn't go straight out and echo it through the class. You can do this, but you would need a whole function, and then you would need to display the function. This isn't as neat, and personally, I like to have a handler:

handler.php
PHP Code

<?php
$OOP 
= new OOP();
?>
Note: Your object should be named after your class. Read the next paragraph for information on objects!

Now, as you can see, we are creating a new object named $OOP (objects are the result of initiating a class) and running it through our handler. If you run this, however, you will get an error. For all of you Java Guru's, this is not like Java anymore, and let me explain:

In PHP, since classes do not have to be named after the file name, you must include the class first. In Java, however, all classes must be named after their filename. This is why in java you do not need to include the file, but only define it.

So, to include our file (for those of you who don't know this), we would do this:

PHP Code

<?php
require_once('class.php'); # once to prevent errors
$OOP = new OOP();
?>

Now it can fetch the class correctly. :)

So, to echo our variable, we would then do this:

PHP Code

<?php 
echo $OOP->variable; # Calls the variable $variable from the object $OOP (class: OOP) 

And Voila, you are done!

Notes/References
  • You cannot echo or do anything of the sort in a class, you can only define variables and functions
  • OOP Can be very confusing to some people, so if you do not get this, I advise you to go read up on it more

Definitions
  • Class: This is a programmer-defined datatype, which includes local functions as well as local data. You can think of a class as a template for making many instances of the same kind (or class) of object.
  • Object: An individual instance of the data structure defined by a class. You define a class once and then make many objects that belong to it. Objects are also known as instance.
  • Constructor: Refers to a special type of function which will be called automatically whenever there is an object formation from a class.

Modifiers
  • Public: Accessible by everything and anything
  • Protected: Accessible only in the same class or classes that extend the class it is in
  • Private: Accessible ONLY in the class it is declared in

Credits
- http://www.tutorialspoint.com/php/php_object_oriented.htm - A good-looking tutorial for OOP users. I got most of the definitions here, but none of my notes were from here. I haven't read it, so feedback would be appreciated
- Eight : Really helped me with some additions and suggestions. :) Shoutout to him.


* - Muhammad Ali - Nov 24, 2012

When i started learning OOP, i needed to re-read the whole introduction and beginning. I don't think anyone will actually get this, as i'm decent with procedural, and already struggled with the basics of OOP and had to read and watch guides on the OOP introduction.

Thus you should make this guide allot longer and advanced.


* - 0xStack - Nov 24, 2012

I think you related things to Java way too much for a PHP section.
Also
public $variable;
$this->variable = "Define Here";

could just be

public $variable = "Define Here";

This isn't really a good subject to teach unless you are highly experienced with all the concepts.
This can't really be considered an introduction, there is way too much to learn.


* - GaBaNo - Nov 24, 2012

I'm planning on building on this tutorial a lot. I referenced it to Java because quite some people that know PHP know Java also, and Java is an OOP language I believe (or, atleast it follows along the guidelines of what makes something OOP)


* - Muhammad Ali - Nov 24, 2012

(Nov 24, 2012 12:48 PM)YvesSaintGreg Wrote:  I think you related things to Java way too much for a PHP section.
Also
public $variable;
$this->variable = "Define Here";

could just be

public $variable = "Define Here";

This isn't really a good subject to teach unless you are highly experienced with all the concepts.
This can't really be considered an introduction, there is way too much to learn.

No, what he does is right, but what you did is right also.

public $variable = "Define Here";

Is the same as $OOP->variable = "Define Here"; .

And that means, you could re-use $Variable anytime you wan't.

So it could be:

PHP Code

<?php 
$Oop
->variable = "First text";
$OOP->variable = "Second text"; 

Short story short, you could re-use variables like an array and echo out different things with the same variable.


* - 0xStack - Nov 24, 2012

(Nov 24, 2012 12:55 PM)Yadinho♡ Wrote:  No, what he does is right, but what you did is right also.

public $variable = "Define Here";

Is the same as $OOP->variable = "Define Here"; .

And that means, you could re-use $Variable anytime you wan't.

So it could be:

PHP Code

<?php 
$Oop
->variable = "First text";
$OOP->variable = "Second text"; 

Short story short, you could re-use variables like an array and echo out different things with the same variable.

If you read his post you will see that he gives the variable data inside the class not in the usage example, therefore our code is equivalent.


* - GaBaNo - Nov 24, 2012

(Nov 24, 2012 12:55 PM)Yadinho♡ Wrote:  No, what he does is right, but what you did is right also.

public $variable = "Define Here";

Is the same as $OOP->variable = "Define Here"; .

And that means, you could re-use $Variable anytime you wan't.

So it could be:

PHP Code

<?php 
$Oop
->variable = "First text";
$OOP->variable = "Second text"; 

Short story short, you could re-use variables like an array and echo out different things with the same variable.

Yes, I edited my tutorial to fit what you guys said. I just remembered getting an error whenever I defined a variable straight away, but now that I redid it, I didn't get the error. Oh well.

You're not as stupid as I thought Yadin. ;)


* - Muhammad Ali - Nov 24, 2012

(Nov 24, 2012 01:00 PM)FallingRain Wrote:  Yes, I edited my tutorial to fit what you guys said. I just remembered getting an error whenever I defined a variable straight away, but now that I redid it, I didn't get the error. Oh well.

You're not as stupid as I thought Yadin. ;)

You should also use Require instead of include, it's just better and more trustier than include.


* - jQuery - Nov 24, 2012

Your code structure is extremely messy and distracts the reader from the main purpose. You should probably stick to 1 file when writing something like this.
I noticed that you used include (as the user above stated), it should not be used. Include only produces a warning if there is an error during the process, whereas require produces a fatal error which will then kill the process.


* - CarrotMilk - Nov 24, 2012

In addition to what has already been said:

I think it's great that you want to make tutorials and try to help out, but something like that been done a million times over. I mean, fair enough if it's a more complicated aspect/side to OOP, but as far as this goes to being "an introduction to OOP", it falls extremely short.


* - GaBaNo - Nov 24, 2012

(Nov 24, 2012 01:25 PM)CarrotMilk Wrote:  In addition to what has already been said:

I think it's great that you want to make tutorials and try to help out, but something like that been done a million times over. I mean, fair enough if it's a more complicated aspect/side to OOP, but as far as this goes to being "an introduction to OOP", it falls extremely short.

I called it an introduction, because it is. It teaches you the basics and generally how to use it. I didn't go in depth that much, I know, but it's still useful to those who don't know what it is.


* - CarrotMilk - Nov 24, 2012

(Nov 24, 2012 01:39 PM)FallingRain Wrote:  I called it an introduction, because it is. It teaches you the basics and generally how to use it. I didn't go in depth that much, I know, but it's still useful to those who don't know what it is.

I'm not trying to flame you at all here, but this doesn't really teach you the basics at all. From the perspective of someone new to the OOP with PHP scene, would this provide any insight into what it's all about? That's why I'm saying it's not an "introduction" because it doesn't introduce what OOP is or does. In addition, there are plenty of other tutorials which DO. It's not a bad thing having more than one tutorial on a particular subject, but, this could be a million times better and what is posted now is practically useless.

I do appreciate you (or anyone else) taking their time to try and help out, I'm just saying, though.


* - GaBaNo - Nov 24, 2012

(Nov 24, 2012 01:44 PM)CarrotMilk Wrote:  I'm not trying to flame you at all here, but this doesn't really teach you the basics at all. From the perspective of someone new to the OOP with PHP scene, would this provide any insight into what it's all about? That's why I'm saying it's not an "introduction" because it doesn't introduce what OOP is or does. In addition, there are plenty of other tutorials which DO. It's not a bad thing having more than one tutorial on a particular subject, but, this could be a million times better and what is posted now is practically useless.

I do appreciate you (or anyone else) taking their time to try and help out, I'm just saying, though.

It's better something then nothing. And I did explain what OOP was, or at least, what it's generally used for and why people prefer it.

Like I said, some of this stuff might be off because I'm new to it too, and all the information I've posted is stuff I've learned without looking at definitions, etc. to learn about it.

I never said you were flaming, either.


* - Eight - Nov 24, 2012

Without trying to sound like a complete douchebag, there are some things I'd like to point out :

> PHP by default is not OOP, you have to make it OOP.
Hmm.. The idea is there but the terminology is not quite right. PHP is a multi paradigm language, meaning you are free to write object oriented or procedural code but the language's structure itself is not fully object oriented and you can't make it so. What I mean to say is that it's not a "mode" that you can activate the the php.ini file or something.

> As you can see, the class name does not have to be the same as the file name, like how it is in java, etc.
It doesn't, but it's highly recommanded especially when making autoloaders for your classes. Look up the PSR standards. Technically nothing prevents you from putting two classes in the same file and giving it a strange name but then you would be coding like a pig.

> As you can see, we defined it using the $this-> method.
Did you try this ? It gave me a syntax error. This syntax is only valid inside your methods. To give your properties a default value, you can simply do public $variable = 3. If the value requires some relatively complex computations (return value of a function or a multi-line associative array or something), then you can do those inside the constructor, or write specific methods for them then call those from your constructor. For example, you can't do public $rand = rand() but you can do :

PHP Code

<?php 
class OOP
{
    public 
$rand;
    public function 
__construct()
    {
        
$this->rand = rand();
    }
} 

> Now, as you can see, we are creating a new instance of the OOP class and running it through our handler.
I think you meant object, an object is the result of instantiating a class.

> And whala, you are done!
Voilà* :^p

In addition to what the other folks said, I would recommand you use require_once instead of require, this will ensure you don't include the same class definition twice and end up with "class already defined in.." errors. That being said, I think this is a very basic tutorial, in an introduction to OOP I would expect at least some basic, uhm, lexicology ? I mean, what a class is, what an object is, what encapsulation is, what methods and properties are, etc. Then some basic syntax, the different visibility keywords and their meaning, inheritance, and maybe abstract classes and interfaces. I attended a few "intro to C++" classes in the university and that's what the teacher taught them, though he began by stating the differences between C & C++.


* - Sir Asylum - Nov 24, 2012

This doesnt really explain OOP at all.
Only 1 little thingy but thats it.