php中类的基本概念

在php中 类这个词语很不陌生,刚开始学习php的时候类这个词语很不好理解,类 对象 方法,变量 很容易搞混。。下面详细介绍下类的概念

打个比方  人类。。动物 。。这就是两个类 。。。哈哈。。这回明确了吧。。。

然后 人类里面有男人 和女人 还有不男不女。。是类里面的对象 就这么简单。

每个类的定义都以关键字 class 开头,后面跟着类名,可以是任何非   PHP 保留字的名字。后面跟着一对花括号,里面包含有类成员和方法的定义。伪变量   $this 可以在当一个方法在对象内部调用时使用。$this   是一个到调用对象(通常是方法所属于的对象,但也可以是另一个对象,如果该方法是从第二个对象内静态调用的话)的引用。看下面例子:例子来源于php100  

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()
   {
       
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);


}
?>

Note:    

   除此之外还有不少用于处理类与对象的函数,详情参见    类 / 对象函数

new

  要创建一个对象的实例,必须创建一个新对象并将其赋给一个变量。当创建新对象时该对象总是被赋值,除非该对象定义了构造函数并且在出错时抛出了一个异常。  

Example #4 创建一个实例e

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

  当把一个对象已经创建的实例赋给一个新变量时,新变量会访问同一个实例,就和用该对象赋值一样。此行为和给函数传递入实例时一样。可以用克隆给一个已创建的对象建立一个新实例。  

Example #5 对象赋值

<?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);
?>

以上例程会输出:

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

extends

  一个类可以在声明中用 extends   关键字继承另一个类的方法和成员。不能扩展多个类,只能继承一个基类。  

  被继承的方法和成员可以通过用同样的名字重新声明被覆盖,除非父类定义方法时使用了   final 关键字。可以通过   parent::   来访问被覆盖的方法或成员。  

Example #6 简单的类继承

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

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

以上例程会输出:

Extending class
a default value

学习是一种信仰

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论