PHP OOP
Object-oriented programming (OOP) is a programming paradigm that uses “objects” – data structures consisting of datafields and methods – and their interactions to design applications and computer programs. Programming techniques may include features such as information hiding, data abstraction, encapsulation, modularity, polymorphism, and inheritance. It was not commonly used in mainstream software application development until the early 1990s. Many modern programming languages now support OOP.
(Source)
Today I’m going to show you the very basic of programming OOP style in PHP5.
Let’s create two files. One named “index.php”, and the other named “class.php”, which is where our php class will go.
Object Oriented Programming’s world orbits around PHP classes. These define and help layout it’s child objects.
Go ahead and open up your favorite code editor and put the following code into your class.php file. Copy & Paste will do, but you might get a better feel for the code if you type it by hand.
<?php
class Text {
var $savedText;
function setText($someText) {
$this->savedText = $someText;
}
function getText() {
return $this->savedText;
}
}
?>
Let’s walk through what just happened there. On line 2 we opened a new class definition named Text. Line 3 made a new internal variable. These variables can be accessed from anywhere inside the class. Lines 4-6 creates a new method called setText. This method gives the $savedText variable the value of $someText. Lines 7-9 create a new method called getText and it returns back whatever the value of $savedText is.
You may be wondering what the $this-> thing is. When used within a class it let’s you access variables and methods from within itself.
Go ahead and open up index.php and paste this into it.
<?php
include('class.php');
$TextClass = new Text();
$TextClass->setText('Hello there!');
echo $TextClass->getText();
?>
Go ahead and run that. You should get “Hello there!” printed to the screen. On line 2 we included the class file so we can use it. On line 3 we created a new instance of the class and assigned it to a variable called $TextClass. On line 4 we set the internal $savedText variable to ‘Hello there!’ via the setText method. On line 5 we printed the result of getText to the screen.
Hopefully you’ve learned the very basics of OOP in PHP. I might write another one of these if I have the time.
