class a{ public $a;//为空,当test()中的$this->a赋值则最后值为1public function test() { $this->a=1; } } $a=new a(); echo $a->a;
基本概念class每个类的定义都以关键字 class 开头,后面跟着类名,可以是任何非 PHP 保留字的名字。后面跟着一对花括号,里面包含有类成员和方法的定义。伪变量 $this 可以在当一个方法在对象内部调用时使用。$this 是一个到调用对象(通常是方法所属于的对象,但也可以是另一个对象,如果该方法是从第二个对象内静态调用的话)的引用。看下面例子:Example #1 面向对象语言中的 $this 变量 <?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. Example #2 简单的类定义 <?php class SimpleClass { // 成员声明 public $var = 'a default value'; // 方法声明 public function displayVar() { echo $this->var; } } ?> Example #3 类成员的默认值 <?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); } ?>
class a{
public $a;//为空,当test()中的$this->a赋值则最后值为1public function test()
{
$this->a=1;
}
}
$a=new a();
echo $a->a;
<?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.
Example #2 简单的类定义
<?php
class SimpleClass
{
// 成员声明
public $var = 'a default value'; // 方法声明
public function displayVar() {
echo $this->var;
}
}
?>
Example #3 类成员的默认值
<?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);
}
?>