开发者

Get function name of child class in parent class

I would like to have a base class with basic properties and functions, so I dont have to define them in all child classes.

I u开发者_JAVA百科se php 5.3.3.

Is this impossible ?

class A {
  private $debug;
  private $var;
  protected function setVar($str) {
    $this->debug = 'Set by function `'. MAGIC_HERE .'` in class `'. get_called_class() .'`.';
    $this->var = $str;
    return true;
  }
  protected function getVar() {
    return $this->var;
  }
  protected function getDebug() {
    return $this->debug;
  }
}
class B extends A {
  public function __construct() {
    $this->doSomething();
  }
  public function doSomething() {
    $this->setVar('my string');
  }
}
$myobj = new B();
$myobj->getDebug();
// expected output "Set by function `doSomething` in class `B`."


<?php
class A {
  private $debug;
  private $var;
  protected function setVar($str) {
    $this->debug = 'Set by function `'. MAGIC_HERE .'` in class `'. get_called_class() .'`.';
    $this->var = $str;
    return true;
  }
  protected function getVar() {
    return $this->var;
  }

  // Notice the public here, instead of protected //
  public function getDebug() {
    return $this->debug;
  }
}
class B extends A {
  public function __construct() {
    $this->doSomething();
  }
  public function doSomething() {
    $this->setVar('my string');
  }
}
$myobj = new B();
echo $myobj->getDebug();
// expected output "Set by function `doSomething` in class `B`."

You had just two small issues. A::getDebug needed to be public to be accessible from the outside and you forgot to output the return of A::getDebug.


See the debug_backtrace function. Note this function is expensive, so you should disable those debug features in production.


Is this no good for you?

I'm not running 5.3 locally, so I had to switch out get_called_class() but you could still use it. Should have made that clear, sorry.

class A {
  private $debug;
  private $var;
  protected function setVar($str, $class) {
    $this->debug = 'Set by function `` in class `'. $class .'`.';
    $this->var = $str;
    return true;
  }
  protected function getVar() {
    return $this->var;
  }
  public function getDebug() {
    return $this->debug;
  }
}
class B extends A {
  public function __construct() {
    $this->doSomething();
  }
  public function doSomething() {
    $this->setVar('my string', __CLASS__);
  }
}
$myobj = new B();
echo $myobj->getDebug();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜