-1

index.php:

<?php
    require("lib.php");

    echo getName();
?>

lib.php:

<?php
    $name = "Matej";

    function getName() {
        return $name;
    }
?>

Code doesnt work, i think its becouse PHP cant get variable form outsite of function. how to fix it?

  • 1) If you write a question with "Code doesnt work", explain *what* doesn't work, what you expect and what you get right now 2) If something doesn't work, add error reporting to the top of each file: `ini_set("display_errors", 1); error_reporting(E_ALL);` and check for errors 3) *"i think its becouse PHP cant get variable form outsite of function"* <- If you already have guess what the problem could be, try to approve / disapprove it. – Rizier123 Apr 03 '16 at 16:57

3 Answers3

0

You can lean about variable scope here. If you want using global variables, then use global keyword.

function getName() {
    global $name;
    return $name;
}

But... well, global is evil. In your case, a function like this is useless. Simply use $name.

Federkun
  • 36,084
  • 8
  • 78
  • 90
0

You're trying to get value of $name outside function, you could call the function sending the value to it and it should work.

Aarón Gutiérrez
  • 1,400
  • 3
  • 16
  • 41
0

The reason is because the variable does not have the global keyword!

$name = 'hello';
function name() {
     return global $name;
}
GradeRetro
  • 38
  • 4