3

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

1 Answer 1

2

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);
  }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for answer! with regards to 1st point, to pass is in function, I've tried that already, but got same php fatal error! With regards to extract method, I have one question: I also pass some varibales to innserFunction. How to pass them in this case?
just declare arguments for innerFuntion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.