0

This wont echo the vars

<?php
function myfunc(){
    function gettime(){
        $date = date('d-m-y h:i:s');
        global $date;
    }
    function getURL(){
        $url = $_SERVER['REQUEST_URI'];
        global $url;
    }
    function getrequest(){
        $method = $_SERVER['REQUEST_METHOD'];
        $request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
        
        switch ($method) {
          case 'PUT': 
            $requestmethod = 'GET';
            break;
          case 'POST':
            $requestmethod = 'POST';
            break;
          case 'GET': 
            $requestmethod = 'GET';
            break;
          default:
          $requestmethod = 'unkown';
            break;
        }
        global $requestmethod;
    }
}
myfunc();
echo $requestmethod.$url.$date;

How can I get $date (and all others) to echo their values?

I set them to Global, and even if I put echo inside of the function, it still didn't work.

user3783243
  • 5,368
  • 5
  • 22
  • 41
QQQ
  • 15
  • 1
  • 6

3 Answers3

0

you are declaring the functions, but you are not calling them.

Try this:

function gettime(){
    $date = date('d-m-y h:i:s');
    global $date;
}
function getURL(){
    $url = $_SERVER['REQUEST_URI'];
    global $url;
}
function getrequest(){
    $method = $_SERVER['REQUEST_METHOD'];
    $request = explode("/", substr(@$_SERVER['PATH_INFO'], 1));
    
    switch ($method) {
      case 'PUT': 
        $requestmethod = 'GET';
        break;
      case 'POST':
        $requestmethod = 'POST';
        break;
      case 'GET': 
        $requestmethod = 'GET';
        break;
      default:
      $requestmethod = 'unkown';
        break;
    }
    global $requestmethod;
}

function myfunc(){
    gettime(); // You invoke the function gettime, so it get executed
    getURL(); // You invoke the function getURL, so it get executed
    getrequest(); // You invoke the function getrequest, so it get executed
}

myfunc();
echo $requestmethod.$url.$date;
gbalduzzi
  • 9,356
  • 28
  • 58
0

The global needs to be first, otherwise it overwrites when called.

For example:

function gettime(){
    global $date;
    $date = date('d-m-y h:i:s');
}

compare https://3v4l.org/M8P7T to https://3v4l.org/irRHf

As noted on the other answer though you also still need to call the functions.

user3783243
  • 5,368
  • 5
  • 22
  • 41
0

You can get it like this:
replace "global" with "return".

function gettime(){
    $date = date('d-m-y h:i:s');
    return $date;
}

instead of using myfunc(); Initiate myFunc() and store it inside a variable as below.

$myFunc = myfunc();

Now you can call all variables and methods inside it example :

echo $myFunc.gettime();