A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")
";
} else {
echo "$this is not defined.
";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
- $this is defined (A)
- $this is not defined.
- $this is defined (B)
- $this is not defined.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…