PHP Object cloning using clone keyword and __clone() magic method

Object cloning or clone of an object means to create a duplicate of an object.
With regular variables $var1 = $var2 means that a new variable $var1 created and have the value of $var2 that means 2 variables created.

 

With objects $obj2 = $obj1 does not mean that a new object i.e. $obj2 get created.

 

When we execute $obj2 = $obj1, the reference of $obj1 is assigned to $obj2. This means that $obj1 and $obj2 point to the same memory space.

So assigning other variables to an object will not actually copy the object, it will simply create a new reference to the same object. In order to truly copy an object, we must use the clone keyword.

[php]
<?php

class House {
private $room_name;

public function setRoomName($room_name) {
$this->room_name = $room_name;
}

public function getRoomName() {
return $this->room_name;
}
}

$obj1 = new House();
$obj1->setRoomName("Bedroom");

$obj2 = $obj1; //only reference or memory assigned

$obj2->setRoomName("Dining Room");

echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>
[/php]

Both will return “Bedroom”

Therefore, to create a new $obj2 object we must “clone” an object to create a new object.

[php]
<?php
$obj2 = clone $obj1;
?>
[/php]

 

After the above line is executed $obj2 with a new memory space is created with the data members having the same value as that of $obj1. This is also referred to as shallow copy.

 

However, this technique will not work with a class that has a data member which is an object of another class (i.e object of an object technique is used). In such a scenario, the cloned object continues to share the reference of the data member object of the class that was cloned.

 

For resolving this we need to use the concept of ‘deep copy’ as opposed to ‘shallow copy’. To implement this you should implement the magic method __clone().

[php]
<?php

class House {
private $room_name;

public function setRoomName($room_name) {
$this->room_name = $room_name;
}

public function getRoomName() {
return $this->room_name;
}

public function __clone() {
$obj = new House();
$obj->setRoomName($this->room_name);
return $obj;
}

}

$obj1 = new House();
$obj1->setRoomName("Bedroom");

$obj2 = clone $obj1; //new object $obj2

$obj2->setRoomName("Dining Room");

echo $obj1->getRoomName();
echo $obj2->getRoomName();

?>
[/php]

 

So, the __clone() magic method allows developers to implement a deep copy of an object when it is cloned.

PHP first performs a shallow clone and the calls the __clone() method on the new object, if it exists, to complete the cloning process.

 

PHP Magic Predefined Constants & usages

PHP Magic Predefined Constants & usages

In PHP, a constant is a name or an identifier for a simple value. A constant name starts with a letter or underscore can be followed by any number of letters, numbers, or underscores. If you have defined a constant, it can never be changed or undefined.

 

You have to use define() function to put value in the constant and for retrieval the value simply specifying the name.
The constant() function can be used if you create the constant name dynamically and want to fetch the value of the constant.

 

[php]
<?php
define("SITENAME", ‘scriptarticle.com’);
echo SITENAME;
echo constant("SITENAME"); // returns the same as previous one
?>
[/php]

 

Along with the above PHP itself have a lot of predefined constants.

Some of the constants that are specials and can be called as magical are listed as below with example, these starts and ends with double underscore (__) and written in capital letters.

The predefined constants are very useful to access information about your code.

 

__LINE__

returns the line number in the code where the constant appears.

 

__DIR__

represents the path to the current file.

 

__CLASS__

returns current class name.

 

__FUNCTION__

returns current function name.

 

__METHOD__

represents the current method name.

 

__NAMESPACE__

returns the current namespace name.

 

__FILE__

represents the name of your file, includes its full path.

 

I have included all these in the below example, have a look.

[php]
<?php

// Set namespace (works only with PHP 5.3 and later)
namespace Scriptarticle;

// this echo current file’s full path and name
echo "This file full path and file name is ‘" . __FILE__;

// this echo file full path
echo "This file full path is ‘" . __DIR__;

// This echo current line number on file
echo "This is line number " . __LINE__;

function function_magic_constant() {
echo "This is from ‘" . __FUNCTION__ . "’ function.";
}

// echo function and used namespace
function_magic_constant();

class SAConstants {
// echo class name
public function printClassName() {
echo "This is " . __CLASS__ . " class";
}
// echo class and method name
public function printMethodName() {
echo "This is " . __METHOD__ . " method";
}
// echo function name
public function printFunction() {
echo "This is function ‘" . __FUNCTION__ . "’ inside class";
}
public function printNamespace() {
echo "Namespace name is ‘" . __NAMESPACE__ . "’";
}
}

// create a object of the class
$obj = new SAConstants;

$obj->printClassName();

$obj->printMethodName();

// this prints function name inside class and used namespace
// same as method name, but without class
$obj->printFunction();

// this prints namespace name
$obj->printNamespace();

?>
[/php]

 

If you want to view a complete list of PHP predefined constant then follow the below links.

PHP Config Predefined Constants
PHP Image Predefined Constants
PHP Date Predefined Constants
PHP Core Predefined Constants
PHP Magic constants

 

Hope you have enjoyed the post!!

 

A Quick view on PHP magic methods

Magic Methods in PHP

(PHP Magical Reserved Functions Starts with double underscore)

According to me you all have heard about the PHP Magic methods.
You have also used some of these like __autoload and __construct.

 

Let’s have a quick view on magic methods, as sometimes it looks like it will hard to use these function but reality is these are very simple.
First of all let me tell what magic method is and why these are called magical? Are these methods really showed some type of magic as the name imply.

 

PHP reserves all function names starting with two underscore prefix (__) as magical.

Magic methods provide hooks into special PHP behavior.

 

PHP does not provide the definitions of the magic functions and the programmers have to write/code that what these functions will do. Magic functions will never directly be called by the programmer but PHP will call the function ‘behind the scenes’. That’s why they are called ‘magic’ functions because these can not be directly called and they allow the programmer to do some powerful things by the coding. I think it’s enough; you will be clearer by examples.

 

__autoload()
This is not a magic method exactly but it is very useful. The __autoload() function is automatically called when a class is instantiated and file will get include in the code. This is useful since you don’t always want to load every class again and again and add just in case you need it to add.

 

__construct()
This magic methods is called when user create object (instances of your class) of the class. Usually this is used for creating constructor in php5.

 

__destruct()
As the name implies, the __destruct() method is called when the object is destroyed by PHP’s garbage collector. It accepts no arguments, and it is usually used to perform memory clean-up operations such as closing a database connection or closing any file.

[php]
<?php

class House{

public function __construct() {
$this->created = time();
$this->logfile = fopen(‘/tmp/log.txt’, ‘w’);
}

public function __destruct() {
fclose($this->logfile);
}
}
$home = new House;
echo $home->created;
?>
[/php]

 

__get
This method is called when your object try attempt to read property or variable of the class which is unavailable or inaccessible.

 

__set
This method called when object of your class attempts to set value of the property which is inaccessible or unavailable in your class.

 

__call
This magic method trigger when you are attempting to call method or function of the class which is either inaccessible or unavailable.

 

__callstatic
This is same as __call executes when inaccessible or unavailable method in static context.

[php]
<?php

class House
{
function __get($name)
{
echo "__get executed as $name is unavailable";
}
function __set($name , $value)
{
echo "__set executed as $name not exists or inaccessible";
}
function __call($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__call executed with name $name , parameter $a";

}
static function __callStatic($name , $parameter)
{
$a = print_r($parameter , true); //taking recursive array in string
echo "__callStatic executed with name $name , parameter $a";

}
}
$a = new House();
$a->abc = 3;//__set executed
$app = $a->myvar;//__get triggerd
$a->getMyinfo(‘mahesh’ , ‘scriptarticle’, ‘blog’);//__call willl executed
House::xyz(‘1’ , ‘sca’ , ‘help’);//__callstatic will executed

?>
[/php]

 

__isset
This magic methods called when isset() function is applied on a property of the class which is inaccessible or unavailable.

 

__unset
This is just opposite of isset method as it called when unset() function called on inaccessible or unavailable property of the class.

[php]
<?php

class House
{
function __isset($name)
{
echo "__isset is called for $name is unavailable";
}
function __unset($name)
{
echo "__unset is called for $name";
}
}
$a = new House();
isset($a->myvar);
unset($a->yourvar);

?>
[/php]

 

__sleep
This method will trigger when you are going to serialize your class’s object.

__wakeup
This will execute when you are un-serializing any class object.

[php]
<?php

class House {
public $name;
public $width;
public $data = array(); // stores misc. data in an array
public $connection; // holds some connection resource

public function __sleep() {
// list the properties to save
return array(‘name’, ’56’, ‘data’);
}

public function __wakeup() {
// reconnect to the house
$this->connect();
}
}
?>
[/php]

 

__toString
This executes when you are using echo on your object.

__invoke
This will trigger when you are using object of your class as function.

[php]
<?php

class House
{
public $myvar;

public function __construct($myvar)
{
$this->myvar = $myvar;
}

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

public function __invoke($x)
{
var_dump($x);
}
}

$object = new House(‘Hello’);
echo $object; // __toString will called
$object(8); // __invoke called
?>
[/php]

 

I have still left some magic methods as __clone(),__set_state() I’ll post a new article for these very soon.

Hope the above one helps you a lot.

 

WordPress .htaccess on Zeus Server Rewrites

WordPress .htaccess on zeus server rewrites (rather than Apache)

Yesterday, I got luck to transfer a WordPress website from one hosting to another.

 

The New hosting provider is http://www.names.co.uk and what I have found is it provides the web server Zeus instead of Apache as always I have worked on.

 

It is really a new experience for me as I have not worked on Zeus server before that.
Let’s discuss what is the main issue I have faced as WordPress move is not a difficult task.

 

You have to export import database and the path updates in database it’s very quick by following some simple queries.

move your wordpress site to a new domain – easy wordpress migration

And the other is just need to transfer files and need to update “wp-config.php”.

That’s it!

 

But what I have faced is, Zeus not supports mod_rewrite as this is a module for Apache servers.
So, Zeus doesn’t support .htaccess files which are required to make your site’s URLs look pretty and SEO friendly (WordPress with its Permalinks).

The file that you need to create is called rewrite.script and is Zeus equivalent to Apache’s .htaccess file.

 

Follow the below steps to work your WordPress site smoothly with permalinks.

The .htaccess File for default WordPress looks like this:

 

[sourcecode language=”plain”]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ – [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
[/sourcecode]

 

Zeus equivalent rewrite.script File

 

[sourcecode language=”plain”]
RULE_0_START:
# get the document root
map path into SCRATCH:DOCROOT from /
# initialize our variables
set SCRATCH:ORIG_URL = %{URL}
set SCRATCH:REQUEST_URI = %{URL}

# see if theres any queries in our URL
match URL into $ with ^(.*)\?(.*)$
if matched then
set SCRATCH:REQUEST_URI = $1
set SCRATCH:QUERY_STRING = $2
endif
RULE_0_END:

RULE_1_START:
# prepare to search for file, rewrite if its not found
set SCRATCH:REQUEST_FILENAME = %{SCRATCH:DOCROOT}
set SCRATCH:REQUEST_FILENAME . %{SCRATCH:REQUEST_URI}

# check to see if the file requested is an actual file or
# a directory with possibly an index. don’t rewrite if so
look for file at %{SCRATCH:REQUEST_FILENAME}
if not exists then
look for dir at %{SCRATCH:REQUEST_FILENAME}
if not exists then
set URL = /index.php?q=%{SCRATCH:REQUEST_URI}
goto QSA_RULE_START
endif
endif

# if we made it here then its a file or dir and no rewrite
goto END
RULE_1_END:

QSA_RULE_START:
# append the query string if there was one originally
# the same as [QSA,L] for apache
match SCRATCH:ORIG_URL into % with \?(.*)$
if matched then
set URL = %{URL}&%{SCRATCH:QUERY_STRING}
endif
goto END
QSA_RULE_END:
[/sourcecode]

 

You can also download the “rewrite.script” file by the below URL.

Download rewrite.script file

Upload “rewrite.script” file to your WordPress root folder (the same folder that contains wp-config.php).

 

If your WordPress site in installed in a sub folder, update line 27 and include the folder to the path before /index.php.

Next you will have to go into the WordPress Settings > Permalinks and save your permalink choice again. This will force WordPress to rebuild the permalinks for the site.

 

You can safely delete the .htaccess file from the remote site as it is no longer needed.

 

I think your site is working now fine but you may notice that you have index.php at the start of all your URLs.
Go to the WordPress settings > Permalinks and update that to a custom structure permalink:

/%category%/%postname%/

 

I think it all works, if you still face any issue post your comments below.