oobie11 oobie11 - 2 months ago 6
PHP Question

How do I make a class variable automatically available to its children classes?

I have an

Application
class and I also have a number of separate classes that extend it. If I set a
$variable
in the parent
Application
class, How do I make it automatically available in its children?

class Application {
public $variable;

public function __construct() {
$this->variable = "Something";
}
}

class Child extends Application {
public function doSomthing() {
$mything = $variable." is cool";
return $mything;
}
}


I know I can put
global $variable;
in my
doSomthing()
method, but that is super tedious to do over and over in every method I write. Is there a way to do it where it just is available to all my child class methods?
Thanks.

Answer

You just set a property named variable in your Application class in __construct method.

If the property visibility permits (e.g. is public or protected), you can access a property potato in any children classes method with $this->potato:

class Application {
    public $variable;

    public function __construct() {
        $this->variable = "Something";
    }
}

class Child extends Application {
  public function doSomthing() {
    $mything = $this->variable." is cool";
    return $mything;
  }
}
Comments