Site Cloner PHP Script
Bargain Hunter PHP Script
Job Hunter PHP Script
Site Login and Access Control PHP Script

PHP Magic Method __toString

The __toString magic method contains the usual double underscore in its front. It does does as its name implies since it strips object characteristics. The next PHP OOP examples should help you understand the details.

Integer Parameter

With the first code block, an integer is passed into the class via the constructor. As you can see, it is an integer before, during and after it leaves the class. But, it is no longer an object and the tests below indicate that.

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

    public function __toString()
    {
        return $this->my_string;
    }
}

$my_array = array('test');
$class = new TestClass(58);
echo $class->my_string;
echo "<br/><br/>";
if (is_object($class->my_string)){
echo "Yes";
}
echo "<br/><br/>";
if ($class->my_string instanceof TestClass) {
   echo "Instance";
}
echo "<br/><br/>";
var_dump($class->my_string);
echo "<br/><br/>";
var_dump((string)$class->my_string);

?>


Browser Output

integer
58
58

int(58)

string(2) “58”

String Parameter

With this example, you can see that if we use the $class->my_string it is a string without any record of its class. But, if you analyze the variable $class, you wil see that it still maintains it association to the class; even though it is a string called my_string with a value of “test”.

<?php

class TestClass
{
    public $my_string;

    public function __construct($my_string)
    {
	    echo gettype($my_string)."<br/>";
        $this->my_string = $my_string;
		echo $this->my_string."<br/>";
    }

    public function __toString()
    {
        return $this->my_string;
    }
}

$class = new TestClass('test');
echo $class;
echo "<br/><br/>";
var_dump($class);
echo "<br/><br/>";
echo var_dump($class->my_string);
echo "<br/><br/>";

if (is_object($class)){
echo "Yes";
}
echo "<br/><br/>";
if ($class instanceof TestClass) {
   echo "Instance";
}

echo "<br/><br/>";
var_dump((string)$class);
$success = settype($class, 'string');
echo (string)$class;
echo "<br/><br/>";
if (!is_object($class)){
echo "No";
}
echo "<br/><br/>";
if (!$class instanceof TestClass) {
   echo "No longer an instance";
}
?>


Browser Output

string
test
test

object(TestClass)#1 (1) { [“my_string”]=> string(4) “test” }

string(4) “test”

Yes

Instance

string(4) “test” test

No

No longer an instance

PHP Magic Methods __SET and __GET

With PHP OOP, you can manually set and get properties when you work with your object, or, you can use the __SET and __GET magic methods which are invoked automatically after you instantiate a class.

If you want guaranteed results and plan to set property names outside the class, making your own functions will allow you to manage public, protected and private properties in this manner.

On the other hand, if you want to print or use properties from a class that are protected or private, you cannot override them with __get and __set magic methods.

The following examples should make this a little more clear.


Manual Get and Set Methods

<?php

class Manual {
public $a = "A";
protected $b = array("a" => "A", "b" => "B", "c" => "C");
 
public function set_var($var){
$this->b = $var;
}

public function get_var(){
return $this->b;
}

}

$m = new Manual();
$var = array("x" => "X", "y" => "Y", "z" => "Z");
//$var = "help";
$m->set_var($var);
echo $m->get_var();
echo "<br/>";
print_r($m->get_var());

?>

Now, I will go over this. The variable was set and returned. Even though the variable $b was protected, the property can be overwritten. However, the same cannot be said for the set_var() and get_var() methods since changing any one of them them to protected or private would not work, thus no value would be returned from the get_var() method.

If you uncomment the line with $var = help, you can change the value from an array to a string. As you can see with this method, $protected $b was overwritten.

Now, let’s move on and try this with __get and __set magic methods.

Magic __get and __set Methods

<?php

class magicMethod {
public $one = "A";
protected $two = array("a" => "A", "two" => "B", "c" => "C");

public $mycount = 0;

public function __get($v) {
$this->mycount = $this->mycount +1;
echo "$v";
return $this->two[$v]; 
}

public function __set($variable, $value){

}
}

$test = new magicMethod();
//$test->one = "TEST"; //can change
//$test->two = "foo"; //cannot change because not public scope inside class
echo $test->one.",".$test->two; 

?>

Here is how this example works. The __set magic method accepts 2 parameters. Meanwhile, the __get magic method accepts and passes on a single parameter. As you can see, the magic methods invoked and printed the $v as two. After that, it printed the public property value for $one followed by the returned value of $this->two[$v].

Now, you may have originally thought that the public value of $one would be followed by the followed by the code from the magic method which output two as as $v and $this->two[$v] as the second value of the protected $two array.

But, the magic methods ran first and output the value of $v which was two. After that, $test->one was printed since it was next in line. After that, the returned value was printed. Since $one was public, it bypassed the __set and __get methods.

If you uncomment the $test->one = “TEST” and $test->two lines, you will see that you can alter the public property but have no luck changing the protected property.

PHP Object Interfaces Keyword

Using object interfaces with PHP OOP is useful when you want to make sure a class must contain specific public functions. In other words, if you want to use an interface for a class, the class must use the method from the interface, otherwise an error will occur.

Another key point to remember with interfaces is that the class and interface code blocks must use public methods with the same amount of parameters. Although the parameters must be the same, the actual names in the interface code block is not that important, asides from good type hinting.

To use interfaces, you make a code block with the interface keyword. This is much like declaring a class, but with a different name. To use the interface conditions in a class, you add the implements keyword followed by the name. The example below should make this clear.

Example #1

<?php

interface example
{
    public function set_name($var1,$var2);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();


Browser Output

Peter Paul


Example #2

Here is an example of code that is slightly modified from above. The only difference is the reduction of one parameter from the interface code block. Thus, ‘public function set_name($var1,$var2)’ was changed to ‘public function set_name($var1)’. The code below would trigger an error because the parameters in the class and interface are different.

interface example
{
    public function set_name($var1);
    public function get_name();
}

Class Test implements example
{
    public $var1;
    public $var2;
    public $var3;
    

    public function set_name($var1, $var2)
    {
        $this->var3 = $var1 . " " . $var2;

    }

    public function get_name()
    {

        return $this->var3;

    }


}

$my_test = new Test();
$my_test->set_name('Peter', 'Paul');
echo $my_test->get_name();

PHP OOP Accessing Protected Properties

When you are using protected properties, they can be accessed with subclasses. However, if you want to print a protected variable from its parent class after you instantiate an object, you will receive a warning message.

The easiest way to explain this is to show the following example. As you can see, if you instantiate an object in the subclass and run a protected method from its parent, you will have access to all properties in the parent class and be able to return it. The reason for this is that the subclass has access to the method of the parent class. Then, the parent class method has access to all properties. However, if the method was private, you would not be able to use the method from the child class.

Besides that, you can output a property from the parent class using echo $test->name;. But, you will not be able to print a protected or private property from the instantiated Form() object. Therefore, printing $test->name2 gives you nothing.

All in all, the usage of public, protected and private properties and methods are what make OOP PHP such a well, organized technique for writing disciplined code.

class Tag
{

    public $name = "Peter";
    protected $name2 = "Paul";
    private $namethree = "Mary";
    private $myvar = "test";

    public function fromparent()
    {
        echo "hey public";
    }

    private function fromprivateparent()
    {
        echo "hey private";
    }

    protected function fromprotectedparent()
    {
        echo "Hey protected variable called: ";
        //$this->myvar = "testin";
        return $this->myvar;
    }

}

class Form extends Tag
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->fromprotectedparent();
        return $this->myvar2;
    }


}

$test = new Form();
echo $test->myvar2 . " \n";
echo "\n";

echo $test->name. " \n";
echo $test->name2. " \n";

PHP OOP Protected Functions

The whole essence of this brief tutorial is to emphasize that fact that protected functions cannot be used by an unrelated class. However, they can be used by a child class. With that said, the block of code will allow you to see a public function that is displayed in another class but the protected function will not. If you changed the line of code protected function from_unrelated_protected() to public function from_unrelated_protected() you will see that the function would work and display output since it is public.

class Tag
{

    public $a;
    public $b;
    public $c;

    public function from_unrelated_class()
    {
        echo "hey public";
    }

    public function from_unrelated_public()
    {
        echo "Hey public variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }

    protected function from_unrelated_protected()
    {
        echo "Hey protected variable called: ";
        $this->myvar = "testin";
        return $this->myvar;
    }


}

class Form
{

    public $test = '';

    function __construct()
    {
        $this->test = new Tag();
        $this->myvar2 = $this->test->from_unrelated_public();
        return $this->myvar2;
    }

    function get_protected(){
        $this->test2 = new Tag();
        $this->myvar3 = $this->test2->from_unrelated_protected();
        return $this->myvar3;
    }


}

$test = new Form();
echo $test->myvar2;
echo $test->get_protected();


Output

OOP Protected Functions PHP

If you do change the line of code:
protected function from_unrelated_protected()
to:
public function from_unrelated_protected()
you will see that the function will display output.

Hey public variable called: testin
Hey protected variable called: testin

PHP Class To Parse Json String

This class can be used to output desired data from a Json string. Here is how it works. The Json string is fed into the constructor within the ParseJson class. Then, the public convert_to_array() function is called while passing in the $this->jsonString property.

Within the function, the Json string is decoded and array is returned. The array takes on the instance name and becomes $my_json->myarray. Thus, the loop which resides outside of the class parses the array using $my_json->myarray as $key => $val.

Class ParseJson
{

    public $jsonString;

    function __construct($json_string)
    {
        $this->jsonString = $json_string;
        $this->convert_to_array($this->jsonString);
    }

    public function convert_to_array($json_string)
    {
        // The second parameter in json_decode has a value of true. This is required to end up with an array.
        $this->myarray = array(json_decode($json_string, true));
        return $this->myarray;

    }


}

$json_string = '[{"A":"MyName","B":"www.example.com","C":"www.example.com/2/"},{"A":"MyName","B":"www.example.ca/","C":"www.example.ca/2/"}]';

$my_json = new ParseJson($json_string);

//print_r($my_json->myarray);

$i = 0;
foreach ($my_json->myarray as $key => $val) {
    $i = $i + 1;

    foreach ($val as $key2 => $val2) {
        echo $key2 . "-" . $val2['B'] . "<br/><br/>";
    }
}
?>

 

Simple Database Connection Class With PHP

This tutorial is a bare bones login class that can be used to connect to a database so that you can execute custom queries. It consists of two files; one contains the actual Login class while the other file will instantiate a new object and gather a variable from that class.

Rundown

The login class has four private properties; $host, $user, $pw and database. The class also uses the constructor which accepts the four arguments. These argumments are set as the properties.

The non-class file sets values for the variables that are passed into a new instantiated object. The code for this is $login = new Login($host, $user, $pw, $database);

Finally, the $db variable is returned using the db_connect() method. Now, the $db variable can be used to query the database. An example query shows how this occurs.

Login Class(class-login.php)

class Login
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


 function db_connect() {
 
 $host = "localhost";
 $user = "user";
 $pw = "password";
 $database = "database_name";

 $db = mysqli_connect($host, $user, $pw, $database) or die("Cannot connect to mySQL."); 

 return $db;
}

}

Other File(login.php)

include("class-login.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new Login($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = "SELECT * FROM tablename ORDER BY id ASC LIMIT 1";
$result = mysqli_query($db, $command);

while ($row = mysqli_fetch_assoc($result)) {
    echo substr($row['name'], 0, 1000);
}

PHP Database Connection Class Using PDO(PHP Data Objects)

The purpose of this two small code snippets is to provide a very lean, simple database connection class that you can use to query your mySQL database using PDO(PHP Data Objects). The coding consists of a pair of files; one of which is the class and the other which is the file which instantiates an object that provides a useful $db variable which can be used to make the queries.

Overview

A new object is instantiated and the database parameters are passed into the constructor. After the parameters are passed in, the db_connect() method is called and it returns the $db. The class does the work of creating a new instance of the PDO object and then returns it with the name $db. Now, $db can be used to do select, insert, update and delete statements. Since you are using a PDO object, you stick with the various methods that are available with the class; such as the execute() method. 

Class File

class DatabaseConnect
{
    private $host;
    private $user;
    private $pw;
    private $database;


    function __construct($host, $user, $pw, $database)
    {
        $this->host = $host;
        $this->user = $user;
        $this->pw = $pw;
        $this->database = $database;
    }


    public function db_connect()
    {
        $db = new PDO('mysql:host=' . $this->host . ';dbname=' . $this->database . '', $this->user, $this->pw) or die("Cannot connect to mySQL.");

        return $db;
    }

}


Other File

include("class-login-PDO.php");

$host = "localhost";
$user = "username";
$pw = "password";
$database = "database_name";

$login = new DatabaseConnect($host, $user, $pw, $database);

$db = $login->db_connect();

var_dump($db);

$command = $db->prepare("SELECT * FROM cms");
$command->execute();
$result = $command->fetchAll();

foreach ($result as $row) {
    $my_array[] = $row;
}

print_r($my_array);