Simon
Simon

Reputation: 23141

Pass parent class static variable in class's method function

I need to pass parent class variable in function which is being called in child class's method.

Please see the code!

class CsBuilder {

     protected static $mysqli = 0;

     private function connect() {
          // make connection
          $mysqli = new mysqli(data);
          self::$mysqli = $mysqli;
     }

     public function initialise() {
          $this->connect();
          // other stuff
     }
}

class App extends CsBuilder {

     public function test() {

          // parent::$mysqli is accessable here!

          function innerFuntion() {
               $query = 'some query';
               // parent::$mysqli->query($query);
               // how to access parent::$mysqli here?
          }

          innerFuntion(); 
     }
}

$builder = new CsBuilder();
$builder->initialise();

$app = new App();
$app->test();

I got follwing error:

PHP Fatal error:  Class 'parent' not found...

Any ideas?

Thanks

Upvotes: 3

Views: 139

Answers (1)

terales
terales

Reputation: 3200

You are trying to use a variable outside of its scope. Check the second example from PHP manual: http://php.net/manual/en/language.variables.scope.php

Here is a fixed code, try it online: http://sandbox.onlinephpfunctions.com/code/80ce967c0b499ce026fbc5d92209c9b8c8cd6323

This is a change:

public function test() {

  // parent::$mysqli is accessable here!

  function innerFuntion($db) {
    var_dump($db);
  };

  innerFuntion(parent::$mysqli); // pass it to the function
}

Warning: using functions inside class methods like you do is a code smell. Consider other approaches:

Light refactor with anonymous functions

In this way, you will ensure that your function is something like macro which will be used in loop of something

public function test() {

  // parent::$mysqli is accessable here!
  $db = parent::$mysqli

  $innerFuntion = function () use ($db) {
    var_dump($db);
  };

  $innerFuntion();
}

The right way: extract method

Extract innerFuntion into a private method, so it won't mess your object's public API but will share object's encapsulated state and would be straightforward to use in test method.

class App extends CsBuilder {

  public function test() {
    $this->innerFuntion('a', 'b');
  }

  private function innerFuntion(arg1, arg2) {
    $query = 'some query';
    parent::$mysqli->query($query);
  }
}

Upvotes: 2

Related Questions