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

WBOY
Release: 2016-06-13 12:04:14
Original
1128 people have browsed it

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

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


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

上面错误的原因是
静态方法调用find的时候,
A类的find里有$this对象,就报错了
请问我的想法能不能实现呢
------解决方案--------------------
虽然不符合规则,但也不是不可以
或许以后还会改变规则呢?自己给自己套枷锁总是没道理的
class A  //核心<br />{<br />    private static $_Instance;<br />    public $db;<br />    public function __construct(){<br />        $this->db=new B();   <br />    }<br />    public function find(){<br />        if(empty(self::$_Instance)) self::$_Instance = new self();<br />        return  self::$_Instance->db->b1();   <br />    }<br />}<br />class B  //数据库<br />{<br />    public function b1(){<br />        return true;<br />    }<br />    public function b2(){<br />        return false;<br />    }<br />}<br />//**********分隔符***********<br />class C extends A //第三方类<br />{<br />   static function test(){<br />     return self::find();   <br />   }<br />}<br /><br />error_reporting(E_ALL ^ E_STRICT);<br /><br />//当前文件<br />if(C::test()){<br />    echo 'OK';   <br />}
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