zoukankan      html  css  js  c++  java
  • 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();
  • 相关阅读:
    centos 6,7 上cgroup资源限制使用举例
    redis sentinel哨兵的使用
    redis发布-订阅
    Golang cpu的使用设置--GOMAXPROCS
    Golang 端口复用测试
    Golang client绑定本地IP和端口
    Go并发控制--context的使用
    Go 并发控制--WaitGroup的使用
    go thrift报错问题--WriteStructEnd
    secureCRT上传本地文件到虚拟机
  • 原文地址:https://www.cnblogs.com/siqi/p/2800601.html
Copyright © 2011-2022 走看看