PHP lessons - introduction to classes and objects - part I

You can think of a class as a needful template that defines an object. It contains functions known as class methods and variables known as class properties/attributes. They are much like the normal php functions and variables:
//example of class property
public $my_name = "test";

//example of class method
function my_method() {
echo "Hello!";
}
Here is an example of a simple class structure: Just copy and paste it in your favorite editor:
<?
class my_class {//begin of class definition

//here we place its functions and variables
public $my_name = "test"; //we are directly setting value of "test" to variable $my_name

function my_method() {
echo $this->my_name; //we are accessing the above class variable $my_name
}

} //end of class my_class
?>
(Note that we've changed the function my_method(). This way when evoked it will display the contents of $my_name. The arrow symbol ( -> ) points to a method or property of a given object. To access our current object, we use the special name $this.)

Next lets create a new object or in other words to make an instance of my_class:
$my_object = new my_class(); //create object from class my_class accessible through variable $my_object
Now the variable $my_object holds a reference to the newly created object of class $my_class. So we could try its methods and properties:
$my_object->my_method(); //will display "test"
$my_object->my_name = "Peter";
echo "<br />";
$my_object->my_method(); //will display "Peter"

Initialization
If we want to initialize our class(i.e. to run some functions or set up some variables) we use its special function called __construct(). Upon exiting our class we use its function __destruct(). Also in the example we restrict the access to our class variable.
Here is an example:
<?php class User{

private $name; //variable $name will be accessible only via methods set_name() and get_name()

function __construct($default_name = "anonymous"){ //initialize $name = "anonymous";
$this->name = $default_name;
}

function set_name($new_name){
$this->name = $new_name; //set $name via incoming parameter $new_name;
}

function get_name(){
return $this->name; //access contents of $name;
}

}

//create object $my_user or make an instance of User
$my_user = new User();

echo "Initial name: " . $my_user->get_name();
echo "<br />";

//now we change $my_user
$my_user->set_name("Ted");
echo "New name: " . $my_user->get_name();
?>

As you can see we've set up out User class: have initialized its default $name via the constructor __construct(), and we have built two functions to manipulate its name(get_name and set_name). Remember that variable $name now can only be accessed by the class methods get_name() and set_name() and not directly: echo $my_user->name will produce an error.

Why private?
Well, it's really a practical question. And the answer is simple: you use 'private' when you have member variables that depend on each other(i.e must change accordingly).
for example if you have:
class User {
public $name; //public means open to direct access
public $avatar;

function set_name($new_name) {
$this->name = $new_name;
$this->avatar = "My name is $this->name. Nice to meet you!";//dependent variable
}
}
$my_user=new User();
$my_user->set_name("John");
$my_user->name="test";
echo $my_user->name;
echo $my_user->avatar;
?>

when $name is 'public' you are allowed to use the direct: $User->name = "John";
but this way you'll ONLY change the variable $name and user's $avatar will not be updated!
Solution: Just set $name to 'private' to disable access such like $User->name and use member function set_name() that automatically updates the dependent variables for you. Now of course you must use the function get_name(); to get the value of variables $name and avatar like for example:
function get_name() {
echo $this->name;
echo "
";
echo $this->avatar;
}
Here is part I of the video from this tutorial:



In lesson 2 we'll explore more advanced topics and practical usage of PHP classes and objects. by Nevyan Neykov



PHP lessons - MySQL class example

<?php
class mysqldb {
//set up the class
var $dbhost;
var $db;
var $dbuser;
var $dbpassword;
var $sql;
var $result;
var $numberrows;
var $dbconnection = false;
var $insert_id;

function get_insert_id(){ $this->insert_id=mysql_insert_id(); return $this->insert_id;}

function getdb(){return $this->db;}

function setdb($req_db){$this->db = $req_db;}

function setdbuser($req_user){$this->dbuser = $req_user;}

function setdbpassword($req_password){$this->dbpassword = $req_password;}

function getsql(){return $this->sql;}

function setsql($req_sql) {$this->sql = $req_sql;}

function getnumberrows() {return $this->numberrows;}

function setnumberrows($req_numberrows) {$this->numberrows = $req_numberrows;}

function setdbconnection($req_dbconnection){$this->dbconnection = $req_dbconnection;}

function closedbconnection(){
if($this->dbconnection=$TRUE) mysql_close($this->dbconnection);
}

function real_escape($string) {
return mysql_real_escape_string($string,$this->dbconnection);
}

function mysqldb(){
$HOST           =    "localhost";
$DB             =    "your_db_name";
$WEBUSER        =    "your_mysql_username";
$WEBPASSWORD    =    "your_mysql_password";
$this->setdb($DB);
$this->setdbuser($WEBUSER);
$this->setdbpassword($WEBPASSWORD);
$this->opendbconnection();
}

function opendbconnection(){
$this->dbconnection=mysql_connect("$this->dbhost","$this->dbuser","$this->dbpassword");
if ($this->dbconnection)//if we have connected select and return true
{
mysql_select_db($this->db,$this->dbconnection) or die("Unable to select database");
}
else {$this->dbconnection=false;}

// unset the data so it couldn't be dumped
$this->dbhost='';
$this->db='';
$this->dbuser='';
$this->dbpassword='';
}

function selectquery(){
$this->qry=@mysql_query($this->sql,$this->dbconnection);
if(!$this->qry){$this->numberrows=0; return false;}//query error

else{//query passed
$this->numberrows=@mysql_numrows($this->qry);
//if we have any result fill in the result array
if($this->numberrows>=0) {
for($x=0;$x<$this->numberrows;$x++){$this->result[$x]=@mysql_fetch_array($this->qry);} return true; }  else{$this->numberrows=0; return false;}//if we don't have results give error
}//end query passed
}
}//end of class mysqldb  
?>  

Here is the explanation of the code: As you can see from the first few lines we are declaring a class. It's name is mysqldb and will hold all our database handling functions such as: opendbconnection(), selectquery(), etc... As you know in Object Oriented Programming these functions are called member functions, because when we create a new 'member', 'object', 'instance'(synonyms in OOP) from this class those functions will automatically attach and belong to the new member.

There are also member variables such as: $dbhost, $db, etc... They are helpful because they are used to exchange data through the all class functions. It's also worth mentioning that every newly created(also called derived in OOP) object could hold its own different data in those variables.
In this database class we'll mainly use member functions to perform various operations and return result such as TRUE, FALSE or a data filled member variable. This way we'll simplify the whole coding process.

But let's first explain the main functions:
function mysqldb() is used to set up our database: host, name and credentials such as username and password needed in order to connect. Their values are being hardcoded as variables, but you could load and use them from another file. Next these variables are set to the object via member functions so they become member variables - accessible from every function inside the class.
Next comes a call to opendbconnection(). As we can see there mysql_connect() uses our member variables to connect to the database host and select the proper database. We have used the variable $dbconnection to show whether our connection has launched successfully. Then we reset our connection variables. This way if somehow our object is hacked and dumped, these variables will be empty, so the attacker won't knew our username and password to gain access to our database.

I. Initial setup example:
Change:
$DB             =    "your_db_name";
$WEBUSER        =    "your_mysql_username";
$WEBPASSWORD    =    "your_mysql_password";
and save the above code as mysql_oop.php

then in a separate php file run:
<?
include_once("mysql_oop.php");
$db= &new mysqldb;
?>
This way we include our database class and create new instance(object) of it. From now on we'll have an access point to that object(or our database) via the variable $db.

II. Selecting, Updating and Deleting data
Function selectquery() is handy because it runs a given sql query and returns its calculated result. In order to use it we must first call function setsql() like this:
<?
$db->setsql("SELECT * from our_table");//fill in the $db->sql variable;
if(!$db->selectquery()) {echo "query returned empty dataset";}
$info = $db->result;
print_r($info);
?>
our result will show up in the $info array. Don't forget to initialize the class first with the 2 lines from our first example. Go ahead and try it!

III. More examples:
Before running a query we must check the input variables. It's easy. For example to check and sanitize the escape characters of variable $password just do:
$new_password=$db->real_escape($new_password);
To get the returned number of rows:
echo $numberrows = $db->getnumberrows();

To debug or show your input sql query code you can use:
echo $db->getsql();
function get_insert_id() displays the id of our last inserted row

and closedbconnection() is used to close the connection to our database server

This object oriented approach is very flexible. Just try the above code and if you have questions go ahead and ask!

Update: please see the following video for working examples:
Next: Try sessions! by Nevyan Neykov



A squared free - best antivirus for 2009

Recently I was having a spyware problem, and this time I decided to look around and retest some of my favourite antivirus software. I tried complex scanning with Dr.Web, Spyware Terminator, AntiMalware from MalwareBytes, Spybot and AdAware.

It appeared that none of them was able to detect the spyware/trojan I was having. I took this as a good sign but then Spyware Terminator Schield warned about some suspicious file trying to access the Internet. The filename was something random such as: 5fdsfgjik.dll and resided on c:\windows\system32\. That looked very suspicious to me, so I blocked the file. I also noticed that when left unblocked, my traffic lights were constantly on, so I located the file and send it to http://virusscan.jotti.org/. Only A-sqared, Icarus and one more software detected the virus. So I download the A-squared free version and cleaned up my computer. Later I found that the A squared took first place in testing executed by www.av-test.org test including 3200 of the most spread malwares with about 480,000 unique malware samples. Here are some details of the 2009 test:

http://www.protectstar-testlab.org/content/site/dateien/1010test-emsi-a-squared_en.pdf

http://www.emsisoft.com/images/antivirustest_pcsl_200907.png

http://malwareresearchgroup.com/?page_id=3

http://ssupdater.com/modules/Forums/index.php?showtopic=5508

2008 test: http://www.pcsecuritylabs.net/articles.php?article_id=4

The following programs were tested:

- Avira Antivir Personal Free Antivirus 9.0
- Bitdefender Free Edition 10
- Panda Cloud Antivirus Beta
- Microsoft Security Essentials 1.0
- Alwil Avast Antivirus Home 4.8
- AVG Anti-Virus Free Edition 8.5
- Emsi Software a-squared Free 4.5
- Comodo Internet Security 3.10
- PC Tools Antivirus Free Edition 6.0
- Clamwin Free Antivirus 0.95

The detection test results for a-squared Free:

- Wildlist Malware on Demand: 100% detected
- Worms: 99.99% detected
- Backdoors: 99.98% detected
- Bots: 99.81% detected
- Trojans: 99.95% detected
- 5 active nasties: 100% detected
- Heuristic (1 week without updates): 63.56% detected
- Heuristic (2 weeks without updates): 52.72% detected
- Adware and Spyware: 99.57% detected

So go ahead and check your computer. It's free for the first 30days.

by Nevyan Neykov