C语言 c++ php mysql nginx linux lnmp lamp lanmp memcache redis 面试 笔记 ppt 设计模式 问题 远程连接

php 未实例化类调用方法的问题

/**
 * 双冒号操作符其意义应该是不实例化类而调用类中的方法或者成员等
 *
 */
class man1
{
    public function show()
    {
        echo "Hello World!";
    }
}
//由于show方法中没有this,所以不出错
man1::show();

class man2
{
    public static $a = 1;
    public function show()
    {
        self::$a;
        echo "Hello World!";
    }
}
//由于show方法中没有this,所以不出错
man2::show();

class man3
{
    public $a = 1;
    public static function show()
    {
        echo $this->a;
        echo "Hello World!";
    }
}
//这种是犯错的,static 方法里面不可以用this
$p = new man3();
$p->show();

注意下面这种写法:

class a
{
    public function show()
    {
        print_r($this);
        echo $this->str;
    }
}
class b
{
    public $str = "Hello World!";
    public function test()
    {
        a::show();
    }
}
/**
 *此处程序运行的结果是输出”Hello World!”
 *因为$this是指向当前类实例化的一个对象,其作用范围为当前对象的上下文
 *而此处A::show()中的$this其实是指向B类实例化的对象 ,而且正在对象上下文中,所以能够输出B中的变量$str的值
 */
$test = new B();
$test->test();

看这种写法:

//自我感觉这个这种写法太绕了,最好不要用
class man1{
    public function run()
    {
        print_r($this);//man2
        $this->say();//由于this为man2实例化的对象,故可以调用man2类中的say方法
        echo 'running';
    }
}

class man2 extends man1{
    public function say()
    {
        echo 'saying';        
    }
}

$p = new man2();
$p->run();

 

 

posted on 2012-12-03 23:45  思齐_  阅读(5810)  评论(0编辑  收藏  举报