1

I have a function:

function page( $variable ) { 

  function display_content() {
     echo $variable;
  }

  require('folder/page.php');

}

As you can see it takes variable and requires a file, but does not do anything with this variable, this function also has another function in it. Then inside 'folder/page.php' i want to call a 'display_content' like:

<?php display_content() ?>

and it won't display anything. THE QUESTION IS: how to put a variable from a "parent" function inside a "child" function as a default argument so that the user can just call a "display_content" function and display $variable inside a "child" function from "parent" function without passing an argument.

  • I know that the question is a little bit complicated, feel free to ask me for explanation. –  Mar 23 '17 at 15:16
  • Because of the scope. – u_mulder Mar 23 '17 at 15:17
  • 1
    There is no such thing as parent functions and child functions in PHP.... what you are doing here is creating a function called `display_content()` in global scope, but only if the `page()` function is called.... after it is created, there is no relationship between the two functions at all, no variable scope sharing, nothing, they are simply two completely independent functions – Mark Baker Mar 23 '17 at 15:19
  • Possible dublicate of http://stackoverflow.com/questions/1631535/function-inside-a-function – Oliver Mar 23 '17 at 15:24
  • @MarkBaker, i know, but is there any solution for things like this in PHP? –  Mar 23 '17 at 15:27
  • The solution is to create `display_content()` as its own function (not inside another function), and to accept a passed argument for what to display, then pass whatever values you need whenyou call it – Mark Baker Mar 23 '17 at 15:35
  • @MarkBaker i want to pass argument inside a function in index.php but then i want to display this value inside other file ( without using echo $something ). It seems like it's impossible, but i've seen something like this in wordpress, i just don't understand how it works.. –  Mar 23 '17 at 15:44
  • When you call the_content(); it displays page content even if you don't pass any argument in it. How to do the same? Some simple example would be enough =) –  Mar 23 '17 at 15:48

1 Answers1

0

These two options are a bit hackish and I wouldn't use them. You really need to think about the design more, but since I'm bored:

function page( $variable ) { 

  $display_content = function() use( $variable ) {
     echo $variable;
  };
  require('folder/page.php');
}

Then in page.php you would call it with the variable:

<?php $display_content(); ?>

Or use a global:

function page( $variable ) {
  $GLOBALS['variable'] = $variable;
  require('folder/page.php');
}

function display_content() {
  echo $GLOBALS['variable'];
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87