
What the heck are Objects and Classes?
Classes, at their simplest point, are just receptacles of functions. They can be compared to a folder on your computer (assuming you aren’t running DOS). Inside the folder you may have three files, or in this case, functions. Let’s use a classic example, a Dog.
Take a look at the following image:

As you can see, a Dog has many “functions”. It can run, walk, sit, play, and bark. This is the essence of what a class is.
An Object, on the other hand, is a way to represent your class. For example, you can have your class named “Dog”, but you can reference it by a variable called Cat if you really wanted to confuse yourself.
That’s all we’re going to cover in this section, so if you’re still confused, read on and I believe the examples will make some coherent sense.
Writing our first class
Since this is just our first class, we’re going to keep things nice and simple. Open up your text editor of choice and make a new file in your web root called myClass.php. Add in the following code:
<?php
class myClass
{
function sayHello()
{
echo "Hello there!";
}
}
?>
If you navigate to this file on your server, nothing will show up. All we did was set up a class (container) and add in a function, we never referenced it to be run.
How to use your freshly written class
Now that we have our myClass.php file all written, we’re going to reference it and use it. Make a new file in the same folder as your class is in, called index.php. Add in the following code:
<?php
require_once('myClass.php');
$myClass = new myClass();
$myClass->sayHello();
?>
If you run the file, you should see “Hello World!” echoed out. Let’s go over what we did to make this work. First, you can see that we required the myClass.php file, which contains our container full of functions. Next, we had to make a new Object, and we used the class name as the object name, just for ease of use. And finally, we referenced our sayHello function by writing the Object name with an arrow and the function name.
Making it Friendlier
Right now, if we wanted to use this to greet a logged in user, there wouldn’t be much of a sense of personalization, would there? Wouldn’t it be nice if we could say Hello to the specific user? Well, we can! Go back to your myClass.php file and edit it accordingly:
<?php
class myClass
{
function sayHello($user)
{
echo "Hello " . $user . "!";
}
}
?>
All we did was add a parameter to the function called name, that we can pass along to the function from our index file. Go back to your index.php file now and add your name like so:
<?php
require_once('myClass.php');
$myClass = new myClass();
$myClass->sayHello('Dixon');
?>
Now, reload your index.php file and you should see a nice textual greeting!
Conclusion
Now that we’ve covered the very basics of Object-Oriented PHP, you can practically do it all. And was it hard? Hopefully not! Be sure to check in later for the rest of this series, in which we’ll be making a fully functional MySQLi Database interaction class! Thanks for reading.
Constructors and Destructors
Think of PHP constructors and destructors like a building. You construct a building at first, then when you’re done using it, you destruct it. Except in PHP, there are no live explosives for the destruction. Let’s look at the following example of constructors:
<?php
class MyClass
{
function __construct()
{
echo "MyClass Loaded!";
}
}
$MyClass = new MyClass();
?>
In this example, we create a new class simply called MyClass, then a constructor function that says MyClass Loaded!. Basically, anything you want to happen when you call upon your class, should go in the constructor function.
In PHP, you don’t need to worry about always having a __destruct() method in your class, as all classes and variables are removed after your object is destroyed. (At the end of execution).
Returning data from your functions
In the real world, you don’t want to be using echo statements within your functions, you want to run your function and return the data for you to echo out where you want it. Let’s take a look at the following example that could be part of a blog application:
<?php
class MyClass
{
var $mysqli;
function __construct()
{
$this->mysqli = new mysqli('localhost', 'root', '', 'blog');
}
function get_latest_posts()
{
//Do some database selection
$query = "SELECT * FROM `posts` ORDER BY `id` DESC";
$result = $this->mysqli->query($query);
return $result;
}
}
?>
Here, we are using a constructor to make a new MySQLi connection, and then using that connection set in the constructor to run a possible query, then to return the result set to be used however you’d like to display the data. Simple, right?
Keeping Organized
In the first part of this series, I described classes as boxes, and functions as the things within the boxes. This picture is a great representation of keeping your classes well separated from each other, and their contents nicely arranged.
One key aspect of writing classes is to keep things easy to read and edit later. Let’s take a look at a file from the very popular blogging platform Wordpress. As you can see, above every variable declaration, class declaration, and function declaration, there is vital information about the parameters, what the function does, and what it returns. Let’s write our own example now:
<?php
/*
* @name MyClass
* @params none
* Our database class that makes a new database connection, and will insert userdata.
*/
class MyClass
{
/*
* MySQLi Connection Link
*/
private $mysqli;
/*
* __construct
* Sets new MySQLi Connection
*/
function __construct()
{
$this->mysqli = new mysqli('localhost', 'root', '', 'buildinternet');
}
/*
* insert_userdata
* @params username, password
* @returns bool
*/
function insert_userdata($username, $password)
{
//Insert the userdata into the database
if(success)
{
return true;
} else {
return false;
}
}
}
php?>
Here, we have said what our class is, what it does, and then defined each function or variable within it. In the insert_userdata() function, we have said what the parameters are and what it returns above the function. As you can already see, these comments help immensely when trying to read your code or trying to find a problem with your code.
Variables and Constructor
Create a new file called class.db.php and insert the following:
<?php
/*
* class db
* @param Host
* @param User
* @param Password
* @param Name
*/
class db
{
var $host; //MySQL Host
var $user; //MySQL User
var $pass; //MySQL Password
var $name; //MySQL Name
var $mysqli; //MySQLi Object
var $last_query; //Last Query Run
/*
* Class Constructor
* Creates a new MySQLi Object
*/
function __construct($host, $user, $pass, $name)
{
$host = $this->host;
$user = $this->user;
$pass = $this->pass;
$name = $this->name;
$this->mysqli = new mysqli($this->host, $this->user, $this->pass, $this->name);
}
}
$db = new db('localhost', 'root', '', 'blog');
?>
**Try and dissect what we have done here before reading the explanation!**
First, we have done the most important part of Object Oriented PHP – organization! We have said what the class name is, and all the parameters that need to be passed to it when it is loaded. Next, inside the class, we have defined our four variables for MySQL connection and then required them as parameters of the constructor function, which can be passed when the class is loaded at the bottom of the file. Next, we have set our $mysqli variable to a new MySQLi Object. Simple, right? Let’s move on.
Main Functions
SELECT
Now that we have the connection down, we can start working with the database. Add a select function like this:
/*
* Function Select
* @param fields
* @param from
* @param where
* @returns Query Result Set
*/
function select($fields, $from, $where)
{
$query = "SELECT " . $fields . " FROM `" . $from . "` WHERE " . $where;
$result = $this->mysqli->query($query);
$this->last_query = $query;
return $result;
}
Here we have made a select function for selecting data from a MySQL table. We have defined three parameters, and you can see how they fit into the final query. All we return from this function is a query result set, which you can work with however you like in your pages.
INSERT
Of course, we can select data with our class now, but we don’t have anything to select unless we insert it! Let’s do that now by adding this function to your class:
/*
* Function Insert
* @param into
* @param values
* @returns boolean
*/
function insert($into, $values)
{
$query = "INSERT INTO " . $into . " VALUES(" . $values . ")";
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
Another quite simple function, we are just requiring two parameters: the table name to insert the data into, and the values for the fields. Instead of returning any real data for this function, we just go ahead and run it and if it inserted the data, it returns true, and if not, false. Simple for inserting data.
DELETE
Now that we can insert and then select our data, we have to have a way to delete it say if a user wanted to delete their account. Add this function:
<?php
/*
* Function Delete
* @param from
* @param where
* @returns boolean
*/
function delete($from, $where)
{
$query = "DELETE FROM " . $from . " WHERE " . $where;
$this->last_query = $query;
if($this->mysqli->query($query))
{
return true;
} else {
return false;
}
}
?>
Some extra goodies
You probably noticed the last_query variable we defined at the beginning of the class, then we set it every time we ran a query in a function. This is very vital for troubleshooting, to see what’s wrong with your query. Another possible class variable could be a last_error, that would hold the last error returned.
Thanks to BuildInternet
Original Source From: http://buildinternet.com/

RSS Feeds
Feed Comment 




0 users responded to this post
2 Pingback & Trackback On This Post
Leave Your Comments Below