-3

I have 2 pages

function.php

function getcookie()
{
    if (!empty($_COOKIE['remember'])) {
        $test="testing function";
    }
}

And home.php

include('function.php');
getcookie();
echo"$test";

I get this error - Notice: Undefined variable: test in .... when I call the getcookie function and meanwhile the cookie is set.

When I try it like this, it works.

home.php

if (!empty($_COOKIE['remember'])) {
    $test="testing function";
}
echo"$test";

Result - testing functon

RiggsFolly
  • 93,638
  • 21
  • 103
  • 149
Ibrahim
  • 99
  • 12
  • 1
    See `Variable Scope` in any language manual. Or [The PHP Manual](http://php.net/manual/en/language.variables.scope.php) – RiggsFolly Jul 16 '18 at 19:54
  • Read about variable scope. Your function doesn't return anything, and defining `$test` inside it doesn't mean it will be defined outside it. – Don't Panic Jul 16 '18 at 19:54
  • @RiggsFolly Personal preference... please don't try to force people to do it "your way". Either way is completely fine. – AStopher Jul 16 '18 at 19:58
  • @cybermonkey If you notice I said "you dont need" I suggested no error or instruction – RiggsFolly Jul 16 '18 at 20:01
  • @cybermonkey But quite frankly why would you force PHP to create a string on the stack and then perform variable substitution upon that unnecessary string literal. Unless yo uhave no respect for your processor cycles – RiggsFolly Jul 16 '18 at 20:03

1 Answers1

0

if you want to echo from inside a function, you can do it like this as one example. Although there are many ways to do this.

function.php

function getcookie(){

    if (!empty($_COOKIE['remember'])) {

        echo "testing function"; // Echo this string

    }

}

Rest of your code

include('function.php');
getcookie(); // This will output "testing function" from inside your function if your condition is met
Simon K
  • 1,503
  • 1
  • 8
  • 10