0

我想有一个具有基本属性和功能的基类,所以我不必在所有子类中定义它们。
我使用 php 5.3.3。

这是不可能的吗?

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`."
4

3 回答 3

0

debug_backtrace功能。请注意,此功能很昂贵,因此您应该在生产中禁用这些调试功能。

于 2010-12-22T16:27:53.867 回答
0

这对你没有好处吗?

我没有在本地运行 5.3,所以我不得不切换出 get_call_class() 但你仍然可以使用它。应该说清楚的,抱歉。

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();
于 2010-12-22T16:30:28.150 回答
0
<?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`."

你只有两个小问题。A::getDebug需要公开才能从外部访问,而您忘记输出A::getDebug.

于 2010-12-22T16:27:22.113 回答