-1

This is really simple but I can't get my head around it. I am setting a datestamp and would like to be able to use it inside a function like this..

    $date_stamp = date("dmy",time());

    function myfunction() {
        echo $date_stamp;
    }

This is not working and $date_stamp is not available inside the function, how can I use this?

John Conde
  • 212,985
  • 98
  • 444
  • 485
fightstarr20
  • 10,259
  • 33
  • 132
  • 247

2 Answers2

3

This is basic PHP. $date_stamp is out of scope within your function. To be in scope you must pass it as a parameter:

$date_stamp = date("dmy",time());

function myfunction($date) {
    echo $date;
}

// call function
myfunction($date_stamp);

See PHP variable scope.

John Conde
  • 212,985
  • 98
  • 444
  • 485
1

Just as an add-on to John Conde's answer, you can also use a closure like so

<?php
$date_stamp = date("dmy",time());

$myfunction = function() use ($date_stamp)  {
    echo '$myfunction: date is '. $date_stamp;
};

$myfunction();
ffflabs
  • 16,563
  • 5
  • 51
  • 75