Home  >  Article  >  Backend Development  >  PHP类中动态方法和静态方法调用写法的不解,希望版主大大指导

PHP类中动态方法和静态方法调用写法的不解,希望版主大大指导

WBOY
WBOYOriginal
2016-06-13 12:04:241158browse

PHP类中动态方法和静态方法调用写法的疑惑,希望版主大大指导

//error_reporting(0);
class A
{
public $db='OK';
private static $_instance;
public static function getInstance()
{
if(!(self::$_instance instanceof self)){
self::$_instance = new self;
}
return self::$_instance;
}
//维持find方法中this指针的写法不变
public function find()
{
echo $this->db;
}
}
class B extends A
{
static function ex()
{
self::getInstance()->find();
}
}
$b=new B();
$b->find();
echo "
";
//第二种方法
B::ex();
?>

根据刚才版主的描述,我稍微修改了一下,做成了现在的效果,不过有点不大明白,因为我也是瞎鼓捣出来的,不明白具体原理
首先A类中的find方法,我想保持它用$this指针的写法,而不要用self
正如我下面的2种调用方法
第一种动态调用find方法,显而易见,输出OK
第二种B是静态类先调用静态方法,返回的是一个“静态实例化对象”?
然后再去调用find方法,这里面我不大清楚,$this指针改变了?
我这么写的作用是让外部代码可以动态调用或静态调用A类中的方法,
就是有点糊涂,瞎鼓捣出来的,
版主能不能整理整理运行原理?
------解决方案--------------------
你在 $b=new B(); 下面加一句
$b->db = 2;

就可看到:虽然是一个类,但却包含两个系统

Statement:
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