Archive

Posts Tagged ‘classes’

Overloading Classes

May 29th, 2010 admin No comments

In OOP, it is a good practice to sometimes “overload” classes if you need to bring in information from the outside. For instance, if you want to include configuration variables in another class, you can “overload” that class with those variables. In this tutorial, I will explain how to do that in both PHP and C++.

Please note, before continuing, that I assume you are an intermediate to advanced C++/PHP programmer. Therefore, I will not go into great detail about how variables are set, etc. because you should already know how that works. We will jump right into the code now for an example as it’s usually the best way to explain these tasks.

PHP

<?php
/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Create our simple class
class OverloadMe
{
/**
* We would like a global var for the whole class
*/
var $var1;

/**
* Constructor
*/
function __construct($name){
$this->var1 = $name;
}

/**
* Name function
*/
function name(){
return $this->var1;
}
}

// Define the name variable
$yourname = "Dennis";

// We overload the function when we initialize it
$overload = new OverloadMe($yourname);

// Now let's get the output
print "Your name is ".$overload->name();
?>

Now, the procedure is very similar in C++, just classes work differently as you already know. I’ll give the C++ code now and explain it all at the end!

C++
src/main.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#include <string>
#include "overload.h"

int main(int argc,char* argv[])
{
std::string name = "Dennis";
OverloadMe overload(name.c_str());
overload.name();
return 0; // exit
}

src/overload.h

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

#ifndef Overload_H
#define Overload_H

// Class definition

class OverloadMe
{
public:
// Constructor
OverloadMe(const char* namevar);

// Name function
void name();
private:
// A global var for the class
const char* var1;
};
#endif

src/overload.cpp

/**
* Class overloading tutorial
* by Dennis J. McWherter, Jr.
*
* (C) 2010 DENNIS J. MCWHERTER JR. All Rights Reserved.
*
*/

// Make the class work
#include <iostream>
#include <stdio.h>
#include "overload.h"

using namespace std;

OverloadMe::OverloadMe(const char* namevar)
: var1(namevar)
{
}

void OverloadMe::name()
{
cout<< "Your name is " << var1 << endl << endl << "Please hit enter to exit" << endl;
getchar();
return;
}

Now, for Windows users using MSVC++, this code will compile with a simple copy/paste. For *nix and BSD users, I’ve included a Makefile within the ZIP package for you to use when compiling. Basically, the compiler must compile each item as an object first, then it must compile the objects into the program file rather than compiling the .exe’s directly.

Well, I hope this is of some use to someone. The examples are fairly simple, but should explain the concept easily. As we can see in the C++ example, we initialize the class to a variable, and simply overload that variable at the time of initialization.

Regards,
Dennis M.

Overload_Tutorial

Categories: C/C++, PHP Tags: , , , , ,

What are PHP Classes and How to Use Them

April 16th, 2009 admin No comments

So some users have been e-mailing me asking me, “What are PHP classes? Why not just use functions?” Well, you could technically just use functions but it makes things messy and insecure. Let me explain. Classes, to oversimplify things a bit, are organizational units within PHP or any other Object Oriented Programming (OOP) language such as C++.

These organizational units, or Classes, hold common functions that you program. They can be used in numerous ways from defining __construct() for everything, or having a private function …() so that nothing outside of members within the class can access the function.

Well, you know what they say; good leading is leading by example. So we’re going to write a quick class and break it down!

<?php
/**
 * Simple class by Dennis M.
 *
 */

// Class definition
class Test
{
	// Define variables here if any.
	var $test = NULL;

	/**
	 * Now, we have two ways to define our constructor.
	 * we can use function __construct() OR we can use
	 * function Test(). If __construct() and Test() are both
	 * used, then the class will use __construct. If not, it
	 * will look for Test(). If neither are defined, we don't
	 * have a constructor XD
	 *
	 */
	function __construct(){
		/**
		 * Define actions in here that will
		 * take place for every function in the class!
		 * If you're not using a DB wrapper, then
		 * you can even define your mysql_connect()
		 * and mysql_select_db() in here so the functions
		 * don't have to do it later!
		 *
		 */
	}

	/**
	 * This next function allows us to print out information
	 * that is returned. Now, we're going to use two functions in here.
	 * The first function that is going to be defined is the public function
	 * for what we want to do. The second function, the check function,
	 * is going to be called within this function, but can only be called by a
	 * script like this because it's private and this function is within
	 * the class.
	 *
	 * It sounds much more confusing than it is in practice :)
	 * let's take a look.
	 *
	 * NOTICE: function text($param='val'). This defines an optional variable
	 *	   when calling the script later. E.g.: text("hello"); or $text();
	 *	   will both work. The first one will use "hello" and the second one
	 *	   will use the default value.
	 *
	 * @return string
	 *
	 */
	function text($say='test'){
		/**
	 	 * Let's run the check first.
		 * The check is a bool function so
		 * when we check for a response, we'll
		 * look for true or false.
		 *
	 	 * Note, because the function is within the
		 * class and it is separate from this one,
		 * we call it using the $this-> operator.
		 *
		 */
		if($this->check($say) != true){
			return "Could not find "".$say."" in the variable \$test.";
		}

		/**
		 * That was our only check. Now, let's
		 * return a success message if
		 * we got passed that!
		 * Realize that 'return' in a function is similar
		 * to an 'exit' in non-function programming.
		 *
		 * Also, return always returns with a value unless
		 * you are creating a VOID function, in which case
		 * you would just use return and no value would come back.
		 *
	 	 */
		return "Success! We found "".$say."" in the variable \$test!";
	}

	/**
	 * Here is the private function we were talking about.
	 *
	 * Private let's us know that no object outside the class "Test"
	 * can use this function.
	 *
	 * @return boolean
	 *
	 */
	private function check($say){
		/**
		 * We defined this variable earlier as
		 * null. Define it as string 'test'
		 * which is what the preceding function
		 * uses by default.
		 *
		 */
		$test = "test";
		if($say != $test){
			return false;
		}
		// That was the only check :)
		return true;
	}
}

// Now we have ended the class but in order to initiate it we
// must define an operator. This is how:
$testclass = new Test;

// Now, we must use pointers to call to functions!
// This will NOT work.
print "Test 1 should fail: ".$testclass->text('w00t!')."<br /><br />";

// This WILL work
print "Test 2 should succeed: ".$testclass->text()."<br />OR
<br />".$testclass->text('test')."<br /><br />";

// This WILL NOT work
print "Test 3 should fail: ";
print $testclass->check('test');

?>

Now I’ve pretty much explained most of what I’m going to cover within the code in the long comments. Now this tutorial is mainly an introduction to classes, but I’d like to leave you guys with a little something more. I’m going to leave this off at the beginning of the “intermediate” level. It’s very difficult to cram EVERYTHING about classes into one post because the possibilities are infinite. So, I’m going to get you started right now on learning more about them and the only way to begin achieving that infinite knowledge is to keep working with them!

You can add the following to the previous code (but make sure it is BEFORE test3 because the error will stop the rest of the script from processing from that point on)

class Test2 extends Test
{
	/**
	 * Note the "extends Test" defined after "class Test2"
	 * This makes Test2 an extension of "Test". In Test2
	 * you are now able to call all functions from Test
	 * using the $this-> operator except for the private
	 * functions. Those are still reserved for the Test class
	 * only.
	 *
	 */
	function w00t(){
		return $this->text();
	}
}

// Define second "test" class
$testclass2 = new Test2;

// This WILL work
print "Test 4 should succeed: ".$testclass2->w00t();

And that about wraps this one up! As usual, for those of you who would rather just download the code, it’s available here:
Classes Tutorial

2 more topics to cover, so get to e-mailing me on what you want to see after those!

Regards,
Dennis M.

Categories: PHP Tags: , , , , , ,