PHP

   »    Free PHP book resources & Tutorials

Computer Education, Training & Tutorial Resources - ComputerEducationWorld.com
Home » Free Computer Books » PHP »

3.8 CLONING OBJECTS
When creating an object (using the new keyword), the returned value is a han-
dle to an object or, in other words, the id number of the object. This is unlike
PHP 4, where the value was the object itself. (more…)


• • •
 

3.7 CLASS CONSTANTS
Global constants have existed in PHP for a long time. These could be defined
using the define() function, which was described in Chapter 2, “PHP 5 Basic
Language.” With improved encapsulation support in PHP 5, you can now
define constants inside classes. (more…)


• • •
 

3.6.4 Static Methods
Similar to static properties, PHP supports declaring methods as static. What
this means is that your static methods are part of the class and are not bound
to any specific object instance and its properties. (more…)


• • •
 

3.6.3 Static Properties
As you know by now, classes can declare properties. Each instance of the
class (i.e., object) has its own copy of these properties. However, a class can
also contain static properties. Unlike regular properties, these belong to
the class itself and not to any instance of it. Therefore, they are often called class properties as opposed to object or instance properties. You can also
think of static properties as global variables that sit inside a class but are
accessible from anywhere via the class.
Static properties are defined by using the static keyword:
class MyClass {
static $myStaticVariable;
static $myInitializedStaticVariable = 0;
}
To access static properties, you have to qualify the property name with
the class it sits in
MyClass::$myInitializedStaticVariable++;
print MyClass::$myInitializedStaticVariable;
This example prints the number 1.
If you’re accessing the member from inside one of the class methods, you
may also refer to the property by prefixing it with the special class name self,
which is short for the class to which the method belongs:
class MyClass {
static $myInitializedStaticVariable = 0;
function myMethod()
{
print self::$myInitializedStaticVariable;
}
}
$obj = new MyClass();
$obj->myMethod();
This example prints the number 0.
You are probably asking yourself if this whole static business is really
useful.
One example of using it is to assign a unique id to all instances of a class:
class MyUniqueIdClass {
static $idCounter = 0;
public $uniqueId;

function __construct()
{
self::$idCounter++;
$this->uniqueId = self::$idCounter;
}
}
$obj1 = new MyUniqueIdClass();
print $obj1->uniqueId . “\n”;
$obj2 = new MyUniqueIdClass();
print $obj2->uniqueId . “\n”;
This prints
1
2
The first object’s $uniqueId property variable equals 1 and the latter
object equals 2.
An even better example for using static property is in a singleton pat-
tern, which is demonstrated in the next chapter.


• • •
 



captcha PHP Script Free PHP captcha script free php
Website Design by WebWalas.com