|
|
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:
Пример 19-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();
?>
|
Результат выполнения данного примера: $this is defined (a)
$this is not defined.
$this is defined (b)
$this is not defined. |
|
Пример 19-2. Simple Class definition |
<?php
class SimpleClass
{
public $var = 'a default value';
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.
Пример 19-3. Class members' default value |
<?php
class SimpleClass
{
public $var1 = 'hello '.'world';
public $var2 = <<<EOD
hello world
EOD;
public $var3 = 1+2;
public $var4 = self::myStaticMethod();
public $var5 = $myVar;
public $var6 = myConstant;
public $var7 = self::classConstant;
public $var8 = array(true, false);
}
?>
|
|
Замечание:
There are some nice functions to handle classes and objects. You might want
to take a look at the Class/Object
Functions.
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).
Пример 19-4. Creating an instance |
<?php
$instance = new SimpleClass();
?>
|
|
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.
Пример 19-5. Object Assignment |
<?php
$assigned = $instance;
$reference =& $instance;
$instance->var = '$assigned will have this value';
$instance = null; var_dump($instance);
var_dump($reference);
var_dump($assigned);
?>
|
Результат выполнения данного примера: NULL
NULL
object(SimpleClass)#1 (1) {
["var"]=>
string(30) "$assigned will have this value"
} |
|
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 within the same name defined in the parent class.
It is possible to access the overridden methods or members by
referencing them with parent::
Пример 19-6. Simple Class Inherintance |
<?php
class ExtendClass extends SimpleClass
{
function displayVar()
{
echo "Extending class\n";
parent::displayVar();
}
}
$extended = new ExtendClass();
$extended->displayVar();
?>
|
Результат выполнения данного примера: Extending class
a default value |
|
patrickr at cyberflowsolutions dot com
29-Oct-2007 02:05
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();
?>
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]);
?>
alan at alan-ng dot net
09-Oct-2007 09:41
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.
somebody at somewhere dot com
25-Sep-2007 08:27
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 = 'foo'; $this->variable = 'foo'; method(); $this->method() ?>
mep_eisen at web dot de
10-Aug-2007 06:06
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;
Stephen
08-Jul-2007 04:54
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 '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';
$a = 2;
var_dump($a);
print '<br>';
var_dump($b);
print '<br>';
var_dump($c);
print '<br><br>';
?>
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.
realbart at hotmail dot com
25-Apr-2007 10:42
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;
}
$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);
echo $XmlRootNode->name; echo $XmlRootNode->firstChild; echo $XmlRootNode->firstChild->name; echo $XmlRootNode->firstChild->nextSibling->name; ?>
Andrew V Azarov
14-Dec-2006 12:20
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; ?>
Dan Dascalescu
26-Oct-2006 11:00
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()
{
...
PHP at Rulez dot com
10-Oct-2005 10:35
Check this!!!
<?php
class foo{
function bar() {
return $this;
}
function hello() {
echo "Hello";
}
}
$foo = new foo();
$foo->bar()->bar()->bar()->bar()->hello();
?>
Haaa! Rulezzz!
chris dot good at NOSPAM dot geac dot com
12-Sep-2005 09:32
Note that Class names seem to be case-insensitive in php 5.
eg
class abc
{
..
{
class def extends ABC
{
..
}
works fine.
tigr at mail15 dot com
01-Mar-2005 04:08
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; echo $object2->id; $object2 = new sampleClass(2);
echo $object1->id; echo $object2->id; $object3 = &$object1; $object3 = new sampleClass(3);
echo $object1->id; echo $object2->id; echo $object3->id; ?>
|