0

I have some functions that work together. But I need to print inside my html some variables used on these functions.

I know I Could:

  • Echo the variable from within the function(function needs to echo it);
  • echo the variable itself (but it needs to be global);
  • Replicate those variables with globals (not a good thing to do);

Is it possible to print a variable that is NOT global, that is inside a function?

File.php

function myFunc()
{
   $var1
   //code...
}

HTML

<td> <?= echo $var1 ?></td>
mega6382
  • 8,624
  • 16
  • 43
  • 65
PlayHardGoPro
  • 2,320
  • 7
  • 36
  • 72
  • Possible duplicate of [PHP function use variable from outside](https://stackoverflow.com/questions/11086773/php-function-use-variable-from-outside) –  Oct 18 '17 at 19:43
  • No, and for a(t least one) good reason. Either make the function return something to be used, or pass that var to that function in first place (by reference if you are really sure what you're doing), or, or, ... [Just don't make it global](https://stackoverflow.com/questions/1557787/are-global-variables-in-php-considered-bad-practice-if-so-why). – Jeff Oct 18 '17 at 19:46
  • Obviously not, which values should it keep if it hasn’t even been allocated? – NoImaginationGuy Oct 18 '17 at 19:47
  • Did the provided solution help? – mega6382 Nov 24 '17 at 10:10

1 Answers1

0

The only way it is possible is by having it declared in global scope. Like:

Method 1: Passing by reference:

<?php
function myFunc(&$var1)
{
   $var1 = 32;
}
myFunc($var1);
?>

<td> <?= $var1 ?></td>

Method 2: Using a globally defined variable inside the function:

<?php

$var1 = 0;
function myFunc()
{
    global $var1;
   $var1 = 32;
}
myFunc($var1);
?>

<td> <?= $var1 ?></td>

Method 3: Returning the variable from the function:

<?php

function myFunc()
{
   $var1 = 32;
   return $var1;
}
$var1  = myFunc($var1);
?>

<td> <?= $var1 ?></td>

Method 4: You can set the variable as enivironment var:

<?php
function myFunc()
{
    $var1 = 32;
    putenv("var1=$var1");
}
myFunc();
?>

<td> <?= getenv('var1') ?></td>

Method 5: You can use the superglobal $_SESSION:

<?php
session_start();
function myFunc()
{
    $var1 = 32;
    $_SESSION['var1'] = $var1;
}
myFunc();
?>

<td> <?= $_SESSION['var1'] ?></td>
mega6382
  • 8,624
  • 16
  • 43
  • 65