Two Basic, quick questions: Regarding functions, includes, and variables

Hi,
I’ve wasted so much time, and this makes no sense, please help.
This simple code is modified slightly, to use variables, and does work:

<?php

// require_once("config2.php");

	function turboGetConnectData()
	{

// Set variables inside the function
$username= "help";
$password= "please";

		return array(
			'server' => 'localhost',
			'type' =>  'mysqli',
			'user' => $username, 
			'password' => $password

This code (almost the same), does not work:

<?php

// require_once("config2.php");

// Set variables outside the function
$username= "help";
$password= "please";

	function turboGetConnectData()
	{

		return array(
			'server' => 'localhost',
			'type' =>  'mysqli',
			'user' => $username, 
			'password' => $password

Setting variables outside the function, doesn’t work? (:
// Obviously, I still have a lot to learn about basic functions.

What I really need to do:
These same variables need to be set from an included file, i.e.

<?php

//  require_once here doesn't seem to work
require_once("config2.php");

	function turboGetConnectData()
	{

//  and / or, ... require_once here *also* doesn't seem to work
require_once("config2.php");

// Set variables inside the function
$username= "var1_from_file";
$password= "var2_from_file";

		return array(
			'server' => 'localhost',
			'type' =>  'mysqli',
			'user' => $username, 
			'password' => $password

This has to be easy, but time slips away, and no combination seems to work. :nono:

  1. For future reference: Why doesn’t the second code block seem to work for setting the variables outside the function?
  2. ‘Urgent’: How can I use similar code, and get the variables from another file?
    Thank you very much. :slight_smile:

Variables have scope, global variables are not accessible from a function, you should pass them in


function turboGetConnectData($name, $pass) {
    // now available
}

turboGetConnectData($username, $password);

You can access them using the global keyword or $GLOBALS array, but better to just pass them in.

Your sample code combined with the link is teaching me exactly what I needed; Thank you for helping ‘hash’.