Home > Backend Development > PHP Tutorial > 类的静态方法在继承中的使用,不大明白,self和this怎么转换?

类的静态方法在继承中的使用,不大明白,self和this怎么转换?

WBOY
Release: 2016-06-23 13:52:08
Original
829 people have browsed it

<?phpclass A  //核心{	public $db;	public function __construct(){		$this->db=new B();		}	public function find(){		return  $this->db->b1();		}}class B  //数据库{	public function b1(){		return true;	}	public function b2(){		return false;	}}//**********分隔符***********class C extends A //第三方类{	 static function test(){		return self::find();		}}//当前文件if(C::test()){	echo 'OK';	}?>
Copy after login


这个文件执行是错的,
只能修改核心和当前文件部分,
我想要当前文件部分那样简短的写法,
不想用$c=new C()
if($c->test()) 这样的写法?

上面错误的原因是
静态方法调用find的时候,
A类的find里有$this对象,就报错了
请问我的想法能不能实现呢


回复讨论(解决方案)

虽然不符合规则,但也不是不可以
或许以后还会改变规则呢?自己给自己套枷锁总是没道理的

class A  //核心{    private static $_Instance;    public $db;    public function __construct(){        $this->db=new B();       }    public function find(){        if(empty(self::$_Instance)) self::$_Instance = new self();        return  self::$_Instance->db->b1();       }}class B  //数据库{    public function b1(){        return true;    }    public function b2(){        return false;    }}//**********分隔符***********class C extends A //第三方类{   static function test(){     return self::find();      }}error_reporting(E_ALL ^ E_STRICT);//当前文件if(C::test()){    echo 'OK';   }
Copy after login
OK


版主果然牛叉,果断收藏

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template