Using global vars within a function in PHP the way you do it in Javascript

后端 未结 5 1858
渐次进展
渐次进展 2021-01-27 15:22

I have a function that uses lots of global vars and arrays - e.g.

$a=1;
$b[0]=\'a\';
$b[1]=\'b\';
$c=\'Hello\';

function foo() {
 echo \"$a 
       $b[0] 
              


        
5条回答
  •  不知归路
    2021-01-27 15:50

    You can use the global keyword:

    $a = "Hello World";
    $b = "Hello World";
    
    function outputStrings(){
      global $a, $b;
      echo $a." - ".$b;
    }
    
    $b = "Goodbye World";
    
    outputStrings(); // ouputs "Hello World - Goodbye World"
    

    However, its best not to use this structure. Its generally confusing and will make your code difficult to maintain. Wordpress uses this approach a lot in their code base and it makes for very tricky debugging. Other plugins and code can interject and modify global variables, changing the output of your script.

    What would be better would be to either:

    Use an OOP structure for your web app.

    This way you can use objects instead of just random global variables. This gets around the issue of you accidentally overwriting a global variable in the course of a script. It also helps to organise the variables correctly, so all variables concerning users can be in the User class. It makes more sense to structure it like that.

    class User {
      private $firstName;
      private $secondName;
      private $gender;
    
      public function __construct($fname, $sname, $gend){
        $this->firstName = $fname;
        $this->secondName = $sname;
        $this->gender = $gend;
      }
    
      public function outputDetails(){
        echo $this->firstName." ".$this->secondName." is ".$this->gender;
      } 
    }
    
    $user = new User("Thomas", "Clayson", "Male");
    $user->outputDetails();
    

    Pass variables into functions

    Just like you've shown in your example. This is the generally accepted standard way of doing this. You should always pass in variables like this, it helps you define scopes and a proper structure. Also it means you know what the value of variables is, as you own them and pass them to functions, rather than just plucking variables from global scope.

提交回复
热议问题