06 February 2008

PHP Programing | PHP Basic | chapter 7 Classes and Object

class
A class is a collection of variables and functions working with these variables. A class is defined using the following syntax:
class Cart {
var $items; // Items in our shopping cart
// Add $num articles of $artnr to the cart
function add_item ($artnr, $num) {
$this->items[$artnr] += $num;
}
// Take $num articles of $artnr out of the cart
function remove_item ($artnr, $num) {
if ($this->items[$artnr] > $num) {
$this->items[$artnr] -= $num;
return true;
} else {
return false;
}
}
}
?>
This defines a class named Cart that consists of an associative array of articles in the cart and two functions to add and remove items from this cart.
Note: In PHP 4 and newer, only constant initializers for var variables are allowed. Use constructors for non-constant initializers.
/* None of these will work in PHP 4. */
class Cart {
var $todays_date = date("Y-m-d");
var $name = $firstname;
var $owner = 'Fred ' . 'Jones';
}

/* This is how it should be done. */
class Cart {
var $todays_date;
var $name;
var $owner;

function Cart() {
$this->todays_date = date("Y-m-d");
$this->name = $GLOBALS['firstname'];
/* etc. . . */
}
}
Classes are types, that is, they are blueprints for actual variables. You have to create a variable of the desired type with the new operator.
$cart = new Cart;
$cart->add_item("10", 1);
This creates an object $cart of the class Cart. The function add_item() of that object is being called to add 1 item of article number 10 to the cart.
Classes can be extensions of other classes. The extended or derived class has all variables and functions of the base class and what you add in the extended definition. This is done using the extends keyword. Multiple inheritance is not supported.
class Named_Cart extends Cart {
var $owner;
function set_owner ($name) {
$this->owner = $name;
}
}
This defines a class Named_Cart that has all variables and functions of Cart plus an additional variable $owner and an additional function set_owner(). You create a named cart the usual way and can now set and get the carts owner. You can still use normal cart functions on named carts:
$ncart = new Named_Cart; // Create a named cart
$ncart->set_owner ("kris"); // Name that cart
print $ncart->owner; // print the cart owners name
$ncart->add_item ("10", 1); // (inherited functionality from cart)
Within functions of a class the variable $this means this object. You have to use $this->something to access any variable or function named something within your current object. Both in and outside of the object you do not need a $ when accessing an object's properties.
$ncart->owner = "chris"; // no $

$ncart->$owner = "chris";
// this is invalid because $ncart->$owner = $ncart->""

$myvar = 'owner';
$ncart->$myvar = "chris";
// this is valid because $ncart->$myvar = $ncart->owner
Constructors are functions in a class that are automatically called when you create a new instance of a class. A function becomes a constructor when it has the same name as the class.
class Auto_Cart extends Cart {
function Auto_Cart () {
$this->add_item ("10", 1);
}
}
This defines a class Auto_Cart that is a Cart plus a constructor which initializes the cart with one item of article number "10" each time a new Auto_Cart is being made with "new". Constructors can also take arguments and these arguments can be optional, which makes them much more useful.
class Constructor_Cart extends Cart {
function Constructor_Cart ($item = "10", $num = 1) {
$this->add_item ($item, $num);
}
}
// Shop the same old boring stuff.
$default_cart = new Constructor_Cart;
// Shop for real...
$different_cart = new Constructor_Cart ("20", 17);
For derived classes, the constructor of the parent class is not automatically called when the derived class's constructor is called.
References inside the constructor
Creating references within the constructor can lead to confusing results. This tutorial-like section helps you to avoid problems.

class foo {
function foo($name) {
// create a reference inside the global array $globalref
global $globalref;
$globalref[] = &$this;
// set name to passed value
$this->setName($name);
// and put it out
$this->echoName();
}

function echoName() {
echo "
",$this->Name;
}
function setName($name) {
$this->Name = $name;
}
}
Let us check out if there is a difference between $bar1 which has been created using the copy = operator and $bar2 which has been created using the reference =& operator...
$bar1 = new foo('set in constructor');
$bar1->echoName();
$globalref[0]->echoName();
/* output:
set in constructor
set in constructor
set in constructor */
$bar2 =& new foo('set in constructor');
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set in constructor
set in constructor
set in constructor */
Apparently there is no difference, but in fact there is a very significant one: $bar1 and $globalref[0] are _NOT_ referenced, they are NOT the same variable. This is because "new" does not return a reference by default, instead it returns a copy.
Note: There is no performance loss (since php 4 and up use reference counting) returning copies instead of references. On the contrary it is most often better to simply work with copies instead of references, because creating references takes some time where creating copies virtually takes no time (unless none of them is a large array or object and one of them gets changed and the other(s) one(s) subsequently, then it would be wise to use references to change them all concurrently).
To prove what is written above let us watch the code below.
// now we will change the name. what do you expect?
// you could expect that both $bar and $globalref[0] change their names...
$bar1->setName('set from outside');

// as mentioned before this is not the case.
$bar1->echoName();
$globalref[0]->echoName();

/* output:
set on object creation
set from outside */

// let us see what is different with $bar2 and $globalref[1]
$bar2->setName('set from outside');

// luckily they are not only equyl, they are thesame variable
// thus $bar2->Name and $globalref[1]->Name are the same too
$bar2->echoName();
$globalref[1]->echoName();

/* output:
set from outside
set from outside */
Another final example, try to understand it.

class a {
function a($i) {
$this->value = $i;
// try to figure out why we do not need a reference here
$this->b = new b($this);
}

function createRef() {
$this->c = new b($this);
}

function echoValue() {
echo "
","class ",get_class($this),': ',$this->value;
}
}


class b {

function b(&$a) {
$this->a = &$a;
}

function echoValue() {
echo "
","class ",get_class($this),': ',$this->a->value;
}

}

// try to undestand why using a simple copy here would yield
// in an undesired result in the *-marked line
$a =& new a(10);
$a->createRef();

$a->echoValue();
$a->b->echoValue();
$a->c->echoValue();

$a->value = 11;

$a->echoValue();
$a->b->echoValue(); // *
$a->c->echoValue();

/*
output:
class a: 10
class b: 10
class b: 10
class a: 11
class b: 11
class b: 11
*/

Article 8
Title : PHP Programing | PHP Basic | chapter 8 References
References are a means in PHP to access the same variable content by different names. They are not like C pointers, they are symbol table aliases. Note that in PHP, variable name and variable content are different, so the same content can have different names. The most close analogy is with Unix filenames and files - variable names are directory entries, while variable contents is the file itself. References can be thought of as hardlinking in Unix filesystem.
PHP references allow you to make two variables to refer to the same content. Meaning, when you do:
$a =& $b
it means that $a and $b point to the same variable.
Note: $a and $b are completely equal here, that's not $a is pointing to $b or vice versa, that's $a and $b pointing to the same place.
The same syntax can be used with functions, that return references, and with new operator (in PHP 4.0.4 and later):
$bar =& new fooclass();
$foo =& find_var ($bar);
Note: Unless you use the syntax above, the result of $bar = new fooclass() will not be the same variable as $this in the constructor, meaning that if you have used reference to $this in the constructor, you should use reference assignment, or you get two different objects.
The second thing references do is to pass variables by-reference. This is done by making a local variable in a function and a variable in the calling scope reference to the same content. Example:
function foo (&$var) {
$var++;
}

$a=5;
foo ($a);
will make $a to be 6. This happens because in the function foo the variable $var refers to the same content as $a
Passing by Reference
You can pass variable to function by reference, so that function could modify its arguments. The sytax is as follows:
function foo (&$var) {
$var++;
}

$a=5;
foo ($a);
// $a is 6 here
Note that there's no reference sign on function call - only on function definition. Function definition alone is enough to correctly pass the argument by reference.
Following things can be passed by reference:
· Variable, i.e. foo($a)
· New statement, i.e. foo(new foobar())
· Reference, returned from a function, i.e.:
function &bar()
{
$a = 5;
return $a;
}
foo(bar());
Any other expression should not be passed by reference, as the result is undefined. For example, the following examples of passing by reference are invalid:
function bar() // Note the missing &
{
$a = 5;
return $a;
}
foo(bar));

foo($a = 5) // Expression, not variable
foo(5) // Constant, not variable
These requirements are for PHP 4.0.4 and later.
Returning References
Returning by-reference is useful when you want to use a function to find which variable a reference should be bound to. When returning references, use this syntax:
function &find_var ($param) {
...code...
return $found_var;
}

$foo =& find_var ($bar);
$foo->x = 2;
In this example, the property of the object returned by the find_var function would be set, not the copy, as it would be without using reference syntax.
Note: Unlike parameter passing, here you have to use & in both places - to indicate that you return by-reference, not a copy as usual, and to indicate that reference binding, rather than usual assignment, should be done for $foo.
Unsetting References
When you unset the reference, you just break the binding between variable name and variable content. This does not mean that variable content will be destroyed. For example:
$a = 1;
$b =& $a;
unset ($a);
won't unset $b, just $a.
Again, it might be useful to think about this as analogous to Unix unlink call.
Spotting References
Many syntax constructs in PHP are implemented via referencing mechanisms, so everything told above about reference binding also apply to these constructs. Some constructs, like passing and returning by-reference, are mentioned above. Other constructs that use references are:
global References
When you declare variable as global $var you are in fact creating reference to a global variable. That means, this is the same as:
$var =& $GLOBALS["var"];
That means, for example, that unsetting $var won't unset global variable.
$this
In an object method, $this is always reference to the caller object.
This is the last chapter I write about PHP but it doesn’t mean that PHP only until this subject because there much more about PHP.and in my article is very litle part from the Big Part of PHP. Next time I will discused about PHP again with more advanced chapter about PHP. Thanks to all my friend for the help writing this article.

Comments :

0 komentar to “PHP Programing | PHP Basic | chapter 7 Classes and Object”


Post a Comment

Please Report me if there's a dead link or invalid link in this post