0

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 use 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`."
j0k
  • 22,600
  • 28
  • 79
  • 90
Kim
  • 2,747
  • 7
  • 41
  • 50

3 Answers3

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

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.

Alin Purcaru
  • 43,655
  • 12
  • 77
  • 90
0

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

Artefacto
  • 96,375
  • 17
  • 202
  • 225
0

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();
DampeS8N
  • 3,621
  • 17
  • 20