1

I want to have a variable that may be used inside and outside of the functions. On PHP manual I found the following example: http://php.net/manual/ro/language.variables.scope.php

<?php
$a = 1;
$b = 2;

function Sum()
{
    global $a, $b;

    $b = $a + $b;
} 

Sum();
echo $b;
?>

Manual says:

The above script will output 3.

But my laravel output for this code (in public show function inside a contreller) is 2.

How to make this work as needed?

TheVic
  • 303
  • 6
  • 16
  • I thought it may be because I try to put this code inside my laravel controller public function show(Plan $plan). – TheVic Mar 19 '19 at 12:02
  • 1
    If the variable is declared within the class it can be accessed with $this-> modifier. If it's a variable outside a class and you want to access it, then it's better to rethink how to access it then to use the `global` keyword. eg, `$result = Sum($a, $b);` - with the method taking two parameters. – Kami Mar 19 '19 at 12:09
  • 1
    Are you able to provide the code that you are actually using? – Kami Mar 19 '19 at 12:09
  • Passing parameters is not a solution, because I have many functions modifying this variables. Pointer parameters would be a solution, but not the best, because I don't want pass this vars, I just want use them as globals. – TheVic Mar 19 '19 at 12:18
  • I'm not too deep in OOP, so I don't know exactly if my var is declared within the class. But $this doesn't work. Anyway, I found the solution. See my answer below. – TheVic Mar 19 '19 at 12:19
  • 1
    Is there a specific reason on why not to return the calculated value and instead replace `$b` (which is one of the used values for calculation) and use as global? **globals** are a "avoid whenever you are able" kind of thing – Diogo Santo Mar 19 '19 at 12:42
  • Okay, i'll think more about it. I'm doing an MRP algorithm, so I have many functions in one big function. Maybe I'll switch to pointer parameters later, for now globals seems to work :) Thank you. – TheVic Mar 19 '19 at 12:54

2 Answers2

4

Try this Code

class TestController extends Controller {

private $search;

public function __construct() {
    $this->search = 1;
}

public function global () {
    echo $this->search;
}
Paras Raiyani
  • 748
  • 5
  • 10
1

I solved it by doing so:

 */
public function show(Plan $plan)
{
    global $a;
    global $b;

    $a = 1;
    $b = 2;

    function Sum()
    {
        global $a, $b;

        $b = $a + $b;
    }

    Sum();
    echo $b.'<br>';

So, the idea is to use global on every function.

TheVic
  • 303
  • 6
  • 16
  • 2
    I would recommend that you review what you are trying to do. In the example you have provided, it's not appropriate to use globals when supplying the values as parameters make more sense. This has been discussed on SO before - https://stackoverflow.com/questions/5166087/php-global-in-functions. YMMV. – Kami Mar 19 '19 at 12:22