Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Language Reference : Classes and Objects (PHP 5) : The Basics

The Basics

class

Every class definition begins with the keyword class, followed by a class name, which can be any name that isn't a reserved word in PHP. Followed by a pair of curly braces, which contains the definition of the classes members and methods. A pseudo-variable, $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs, but can be another object, if the method is called statically from the context of a secondary object). This is illustrated in the following examples:

Example 10.1. $this variable in object-oriented language

<?php
class A
{
   function
foo()
   {
       if (isset(
$this)) {
           echo
'$this is defined (';
           echo
get_class($this);
           echo
")\n";
       } else {
           echo
"\$this is not defined.\n";
       }
   }
}

class
B
{
   function
bar()
   {
       
A::foo();
   }
}

$a = new A();
$a->foo();
A::foo();
$b = new B();
$b->bar();
B::bar();
?>

The above example will output:

$this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined.


Example 10.2. Simple Class definition

<?php
class SimpleClass
{
   
// member declaration
   
public $var = 'a default value';

   
// method declaration
   
public function displayVar() {
       echo
$this->var;
   }
}
?>


The default value must be a constant expression, not (for example) a variable, a class member or a function call.

Example 10.3. Class members' default value

<?php
class SimpleClass
{
   
// invalid member declarations:
   
public $var1 = 'hello '.'world';
   public
$var2 = <<<EOD
hello world
EOD;
   public
$var3 = 1+2;
   public
$var4 = self::myStaticMethod();
   public
$var5 = $myVar;

   
// valid member declarations:
   
public $var6 = myConstant;
   public
$var7 = self::classConstant;
   public
$var8 = array(true, false);
   
   
}
?>


Note:

There are some nice functions to handle classes and objects. You might want to take a look at the Class/Object Functions.

new

To create an instance of a class, a new object must be created and assigned to a variable. An object will always be assigned when creating a new object unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

Example 10.4. Creating an instance

<?php
$instance
= new SimpleClass();
?>


In the class context, it is possible to create a new object by new self and new parent.

When assigning an already created instance of a class to a new variable, the new variable will access the same instance as the object that was assigned. This behaviour is the same when passing instances to a function. A copy of an already created object can be made by cloning it.

Example 10.5. Object Assignment

<?php
$assigned  
=  $instance;
$reference  =& $instance;

$instance->var = '$assigned will have this value';

$instance = null; // $instance and $reference become null

var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>

The above example will output:

NULL
NULL
object(SimpleClass)#1 (1) {
  ["var"]=>
    string(30) "$assigned will have this value"
}


extends

A class can inherit methods and members of another class by using the extends keyword in the declaration. It is not possible to extend multiple classes, a class can only inherit one base class.

The inherited methods and members can be overridden, unless the parent class has defined a method as final, by redeclaring them with the same name defined in the parent class. It is possible to access the overridden methods or static members by referencing them with parent::

Example 10.6. Simple Class Inheritance

<?php
class ExtendClass extends SimpleClass
{
   
// Redefine the parent method
   
function displayVar()
   {
       echo
"Extending class\n";
       
parent::displayVar();
   }
}

$extended = new ExtendClass();
$extended->displayVar();
?>

The above example will output:

Extending class
a default value


Related Examples ( Source code ) » language.oop5.basic


Code Examples / Notes » language.oop5.basic

alan

The following odd behavior happens in php version 5.1.4 (and presumably some other versions) that does not happen in php version 5.2.1 (and possibly other versions > 5.1.4).
<?php
$_SESSION['instance']=...;
$instance=new SomeClass;
?>
The second line will not only create the $instance object successfully, it will also modify the value of $_SESSION['instance']!
The workaround I arrived at, after trial and error, was to avoid  using object names which match a $_SESSION array key.
This is not intended to be a bug report, since it was apparently fixed by version 5.2.1, so it's just a workaround suggestion.


patrickr

Running on PHP v5.2.3 / Zend v2.2.0...
When creating a new variable and if you use the same scalar name, the 'pointer' ID doesn't update.
<?php
class testObj {
public $val;

function __construct($var) {
$this->val = $var;
}
}
class testList {
private $list;

function create(&$obj) {
$this->list[] =& $obj;
}

function get($id) {
return $this->list[$id];
}

function display() {
var_dump($this->list);
}
}
$theList = new testList();
$obj = new testObj("this value is set");
$theList->create($obj);
$obj = new testObj("but what about this one?");
$theList->create($obj);
echo "[Obj1]) " . $theList->get(0)->val . "\n";
echo "[Obj2]) " . $theList->get(1)->val . "\n";
$var = $theList->get(0);
echo "[\$var]) " . $var->val . "\n";
echo "[Obj1]) " . $theList->get(0)->val . "\n";
echo "[Obj2]) " . $theList->get(1)->val . "\n";
$var->val = "we are changing the value";
echo "[\$var] " . $var->val . "\n";
echo "[Obj1] " . $theList->get(0)->val . "\n";
echo "[Obj2]) " . $theList->get(1)->val . "\n";
$theList->display();
// OUTPUT
/*
[Obj1]) but what about this one?
[Obj2]) but what about this one?
[$var]) but what about this one?
[Obj1]) but what about this one?
[Obj2]) but what about this one?
[$var] we are changing the value
[Obj1] we are changing the value
[Obj2]) we are changing the value
array(2) {
 [0]=>
 &object(testObj)#3 (1) {
   ["val"]=>
   string(25) "we are changing the value"
 }
 [1]=>
 &object(testObj)#3 (1) {
   ["val"]=>
   string(25) "we are changing the value"
 }
}
*/
?>
Therefore, using an array to preload where new() is referecing the data from is recommended when creating arrays of references from a loop.
<?php
$obj = array();
$obj[0] = new testObj("this value is set");
$theList->create($obj[0]);
$obj[1] = new testObj("but what about this one?");
$theList->create($obj[1]);
// OUTPUT
/*
[Obj1]) this value is set
[Obj2]) but what about this one?
[$var]) this value is set
[Obj1]) this value is set
[Obj2]) but what about this one?
[$var] we are changing the value
[Obj1] we are changing the value
[Obj2]) but what about this one?
array(2) {
 [0]=>
 &object(testObj)#2 (1) {
   ["val"]=>
   string(25) "we are changing the value"
 }
 [1]=>
 &object(testObj)#3 (1) {
   ["val"]=>
   string(24) "but what about this one?"
 }
}
*/
?>


andrew v azarov

Remember that $this->var and $this->$var are different
when using smth like
<?
class test
{
       var $var;
       function Setvar()
       {
                $this->$var = "test";
       }
}
$m = new test();
$m->Setvar();
$m->var;
?>
will result in an fatal error or empty var
do instead
<?
$this->var = "test";
?>
then u may access it like <? $m->var; ?>


mep_eisen

referring to steven's post:
****
Perhaps this is because =& statements join the 2 variable names in the symbol table, whereas = statements applied to objects simply create a new independent entry in the symbol table that simply points to the same location as other entries. I don't know for sure - I don't think this behavior is documented in the PHP manual, so perhaps somebody with more knowledge of PHP's internals can clarify what is going on.
****
lets talk about
a =& b;
b = c;
PHP internally marks a to be a reference to b. If You reassign b PHP does not update a. But if you access a once more PHP looks at the current value of b (now containing c).
Both statements (a=b and a=&b) seem to do the same but they don't. However this changed for objects from PHP4 to PHP5. Where PHP4 needed this operator to avoid object cloning, PHP5 does not need it.
It is explained in chapter 21 (References Explained). It's important to understand that a becomes a reference and the following code will not modify b:
a =& b;
a =& c;


tigr

Objects are not being passed by reference as varables do. Let me try to explain:
Variable passing by reference means that two variables are being binded together, so that changing one variable leads to changes in the other. In fact, there is only one variable.
Object passing by reference is a bit different. It means that not the object itself is being passed (that would lead to copying it and all evil), but only reference to the object is being passed. Now, both VARIABLES point to the same object, BUT they DO NOT point to each other. There are TWO DIFFERENT variables. This means that if you change one VARIABLE, second one would still point to the same object.
So, adding reference operator still has some sense. Here is an example:
<?php
class sampleClass {
   public $id;
   public function __construct($id) { $this->id=$id; }
}
$object1 = new sampleClass(1);
$object2 = $object1;
echo $object1->id; // 1
echo $object2->id; // 1
$object2 = new sampleClass(2);
echo $object1->id; // 1 So, $object1 was not changed. It still links
                  // to the same object
echo $object2->id; // 2
$object3 = &$object1; // note the reference operator
$object3 = new sampleClass(3);
echo $object1->id; // 3 This time $object one was changed since it
                  // was bound with $object3
echo $object2->id; // 2
echo $object3->id; // 3
?>


chris dot good

Note that Class names seem to be case-insensitive in php 5.
eg
class abc
{
..
{
class def extends ABC
{
..
}
works fine.


stephen

jcastromail at yahoo dot es stated:
****
in php 5.2.0 for classes
$obj1  =  $obj2;
is equal to
$obj1  =  &$obj2;"
****
However, that is not completely true. While both = and =& will make a variable refer to the same object as the variable being assigned to it, the explicit reference assignment (=&) will keep the two variables joined to each other, whereas the assignment reference (=) will make the assigned variable an independent pointer to the object. An example should make this clearer:
<?php
class z {
public $var = '';
}

$a = new z();
$b   =&  $a;
$c  = $a;
$a->var = null;
var_dump($a);
print '
';
var_dump($b);
print '
';
var_dump($c);
print '
';
$a = 2;
var_dump($a);
print '
';
var_dump($b);
print '
';
var_dump($c);
print '
';
?>
This outputs:
object(z)#1 (1) { ["var"]=>  NULL }
object(z)#1 (1) { ["var"]=> NULL }
object(z)#1 (1) { ["var"]=> NULL }
int(2)
int(2)
object(z)#1 (1) { ["var"]=> NULL }
So although all 3 variables reflect changes in the object, if you reassign one of the variables that were previously joined by reference to a different value, BOTH of those variables will adopt the new value.
Perhaps this is because =& statements join the 2 variable names in the symbol table, whereas = statements applied to objects simply create a new independent entry in the symbol table that simply points to the same location as other entries. I don't know for sure - I don't think this behavior is documented in the PHP manual, so perhaps somebody with more knowledge of PHP's internals can clarify what is going on.


somebody

It should be noted that PHP, unlike many other OO languages (C++, Java, etc.), doesn't push all members to the global namespace while inside a method, so when accessing members, going through $this to do so is NOT optional.
Example:
<?php
// $variable and method() are a member variable and a member function, respectively
$variable = 'foo'; // wrong
$this->variable = 'foo'; // right
method(); // wrong
$this->method() // right
?>


dan dascalescu

If E_STRICT is enabled, the first example will generate the following error (and a few others akin to it):
Non-static method A::foo() should not be called statically on line 26
The example should have explicitly declared the methods foo() and bar() as static:
class A                                                                                                                            
{                                                                                                                                  
   static function foo()                                                                                                          
   {
...


realbart

Classes do not seem to be passed to functions. correctly in PHP4
I'll let you know when I find out why
<?php
class XmlNode
{
var $name;
var $attrs;
var $parentNode;
var $firstChild;
var $nextSibling;
}
function startElement($parser, $name, $attrs)
{
global $XmlRootNode;
global $XmlPreviousSibling;
global $XmlParentNode;
if (is_null($XmlRootNode))
{
$XmlRootNode = new XmlNode;
$currentNode = &$XmlRootNode;
}
else
{
if (is_null($XmlParentNode->firstChild))
{
$XmlParentNode->firstChild = new XmlNode;
$currentNode = &$XmlParentNode->firstChild;
}
else
{
$XmlPreviousSibling->nextSibling = new XmlNode;
$currentNode = &$XmlPreviousSibling->nextSibling;
}
$currentNode->parentNode = &$XmlParentNode;
}
$currentNode->name = $name;
$currentNode->attrs = $attrs;
$XmlPreviousSibling = &$currentNode;
$XmlParentNode = &$currentNode;
echo $XmlParentNode->name;
}
function endElement($parser, $name)
{
global $XmlParentNode;
$XmlParentNode = &$XmlParentNode->parentNode;
}
// nothing wrong with these lines
$file = "vragen.xml";
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
if (!($fp = fopen($file, "r"))) die("could not open XML input");
while ($data = fread($fp, 4096)) if (!xml_parse($xml_parser, $data, feof($fp)))
die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));
xml_parser_free($xml_parser);
//the xml file should now be converted to xml nodes...
echo $XmlRootNode->name; // returns the name of the root object
echo $XmlRootNode->firstChild; // should return "Object" yet returns nothing.
echo $XmlRootNode->firstChild->name; // shoud return the name of the first object but doesn't
echo $XmlRootNode->firstChild->nextSibling->name; //also returns nothing
?>


php

Check this!!!
<?php
class foo{
 function bar() {
   return $this;
 }
 function hello() {
   echo "Hello";
 }
}
$foo = new foo();
$foo->bar()->bar()->bar()->bar()->hello();
?>
Haaa! Rulezzz!


Change Language


Follow Navioo On Twitter
Introduction
The Basics
Autoloading Objects
Constructors and Destructors
Visibility
Scope Resolution Operator (::)
Static Keyword
Class Constants
Class Abstraction
Object Interfaces
Overloading
Object Iteration
Patterns
Magic Methods
Final Keyword
Object cloning
Comparing objects
Reflection
Type Hinting
Late Static Bindings
eXTReMe Tracker