-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
  • 217,595
  • 99
  • 455
  • 496
fightstarr20
  • 11,682
  • 40
  • 154
  • 278

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
  • 217,595
  • 99
  • 455
  • 496
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
  • 17,166
  • 5
  • 51
  • 77