php学习笔记(一)————php类的概念

<?php
//类的概念
/*
 * 一个类包含自己的属性和函数
 * 
 * 属性:属于类自己的常量和变量
 * 
 * 方法:就是函数
 * 
 * 类是一类事物的抽象
 */
//例子:
//车就是一种抽象
class Car{
    //车的基本属性:有轮子,有颜色,可以拉货(人)    
    public $color = 'red';//默认红色
    public $wheel_size = 4;//默认4个
    
    //方法:拉货默认
    public function pull_some_thing($something = '货'){
        echo "我是一辆 $this->color 色的,有 $this->wheel_size 个轮子的车,我正在拉 $something ";
    }
}

$qiche  = new Car();
$qiche->color = '黑';
$qiche->wheel_size = 12;
$qiche->pull_some_thing('人');

echo '<hr/>';


//例子2:
class A
{
    function foo()
    {
        if (isset($this)) {
            echo '$this is defined (';
            echo get_class($this);//获得这个$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();//在b类下调用A类的foo方法,获得的$this 是B类
    }
}

$a = new A();
$a->foo();

@A::foo();//直接在类外调用A类的foo方法不能获取到A类(就是说不能在类外使用$this指代目标类)
//$this->foo();//会报错

$b = new B();
@$b->bar();

// Note: the next line will issue a warning if E_STRICT is enabled.
@B::bar();

echo '<br/>';

执行效果 

原文地址:https://www.cnblogs.com/wobeinianqing/p/7018634.html