1
<?php
function datas($value){
$sum = 10 + $value;
return $sum;
}
echo datas(2);
?>

It would give me 12 however I wanted to call the var $sum outside of the function like

<?php
function datas($value){
$sum = 10 + $value;
return $sum;
}
echo datas(2);

echo $sum;
?>

How do I do that?

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
  • Simply use assignment `$sum = datas(2);` This would not reference the same `$sum` which is inside the function's body due to variables scoping, but instead it will create a new `$sum` variable outside the function's scope, which is desired outcome anyways, right? – Nemoden Feb 04 '20 at 01:16
  • @Nemoden thank you very much! It's a huge help for me – user12105480 Feb 04 '20 at 01:24

2 Answers2

1

In PHP, variable declaration has context inside { } like so: method() {var} You can assign the result of this function to a variable in outside scope

the below code is example

<?php
 function datas($value){
 $sum = 10 + $value;
 return $sum;
 }
 echo datas(2);
 // $sum is null or blank
 echo $sum;
 ?>

Example correct for reference the var

<?php

 function datas($value){
 $sum = 10 + $value;
 return $sum;
 }
 $sum = datas(2);
 // $sum is not null or blank
 echo $sum;
?>
// OR

<?php
class SaveData {
    public $sum=0;
    public function myMethod($value) {
        $this->sum = 10 + $value;
        return $this->sum;
        }
}
$d = new SaveData();
$d->myMethod(2);
echo $d->sum;
?>

Evgenii Klepilin
  • 695
  • 1
  • 8
  • 21
0

You most likely look for global keyword:

$sum = 0;

function datas($value){
    global $sum;
    $sum = 10 + $value;
    return $sum;
 }
 echo datas(2);
 echo $sum;

but I'd rather strongly recommend not doing that as this is the shortest way to problems. Limiting variable scope, encapsulation, OOP exists for a reason.

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141