We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 11376
    • 1 Posts
    Hi all,

    Is there any reason why the following code wont work?

    <?php
    $user = 'user';
    	$pass = 'pass';
    
    	function test() {
    		global $user, $pass;
    		return $user.$pass;
    	}
    	echo test();
    ?>
    


    I am using this in a snippet, and it doesn’t do anything yet if I pass $user and $pass as a variable it will work:

    ie

    <?php
    $user = 'user';
    	$pass = 'pass';
    
    	function test($user, $pass) {
    		return $user.$pass;
    	}
    	echo test($user, $pass);
    ?>
    


    Am I missing something?

    Also, is there anyway you can get the username and password used to connect to the mysql database? I am currently having to manually type in the same database details as those used for modx.

    Cheers
      • 11975
      • 2,542 Posts
      <?php
      
      global $user, $pass;
      
      $user = 'user';
      	$pass = 'pass';
      
      	function test() {
      		global $user, $pass;
      		return $user.$pass;
      	}
      	echo test();
      ?>
      


      should work better

      :-)
        Made with MODx : [url=http://www.copadel.com]copadel, fruits et l
        • 22303 MODX Staff
        • 10,725 Posts
        BTW, you can also test for the presence of and access global variables using the superglobal array $GLOBALS. This is my preferred method of dealing with globals, if I must. Honestly, I avoid dependencies on global variables in most cases; it really does promote poor coding practices. But you likely will need to declare the variables global first, as heliotrope suggests.

        <?php
        global $user, $pass;
        $user = 'user';
        $pass = 'pass';
        function test() {
            return $GLOBALS['user'].$GLOBALS['pass'];
        }
        echo test();