Changes

Jump to: navigation, search

Object Oriented Programming with Visual Basic

2,277 bytes removed, 18:15, 8 August 2007
PHP Object Serialization
The result will a message which reads "John Smith has balance of 1225", since the account fee has now been subtracted from the balance.
== PHP Object Serialization ==
One of the interesting features of object oriented programming is the ability to take a snapshot of the current state of an object and then save that object to a file, or even transmit it over a network to another process where it will be re-activated. This concept is known in the object oriented world as ''object serialization''.
 
All objects have built-in method called ''__sleep'' that is called before serialization. If you need your object to perform any housekeeping before being serialized you will need to override this method.
 
An object is serialized using the ''serialize()'' function and unserialized, not surprizsingly, using the ''unserialize()'' function. As an example we can serialize our bankAccount object:
 
<pre>
<?php
class bankAccount {
 
private $accountNumber;
private $accountname;
 
public function __construct($acctNumber, $acctName) {
$this->accountNumber = $acctNumber;
$this->accountname = $acctName;
}
 
public function __destruct() {
}
 
public function setAccountNumber($acctNumber)
{
$this->accountNumber = $acctNumber;
}
 
public function setAccountName($acctName)
{
$this->accountName = $acctName;
}
 
public function getAccountName()
{
return $this->accountName;
}
 
public function getAccountNumber()
{
return $this->accountNumber;
}
 
}
 
$myObj = new bankAccount('246810', 'Morgan Freeman');
 
$serialized = serialize ($myObj);
 
echo 'Object is serialized<br>';
 
$newObj = unserialize ($serialized);
 
echo 'Object is unserialized<br>';
 
print_r ($newObj);
?>
</pre>
 
In the above example the object is serialized, then unserialized to a new object variable. We then use the ''print_r()'' function to verify the new object contains everything the old one did resulting in the following output:
 
<tt>
Object is serialized<br>
Object is unserialized<br>
bankAccount Object ( [accountNumber:private] => 246810 [accountname:private] => Morgan Freeman )<br>
</tt>
 
Once we have the serialized data in our $serialized we can do anything we want with it, such as write it to a file or send it through a network socket to another process where it can be unserialized and used.
== Getting Information about a PHP Object ==

Navigation menu