-1

I have a func.inc file as below

// STATUS_VALLUE
$status_failure = 0;
$status_success = 1;

function resultResultJson($status) {
    echo $status;
    echo $status_success;
}

And my function.php as below

<?php 
    include("./includes/func.inc");
    resultResultJson($status_success);
?>

I'm expected result 11. But I got 10. Why is the function resultResultJson not getting the right $status_success result?

Updated

The https://stackoverflow.com/a/16959577/3286489 provides explanation on the variable scope, which explains why, but doesn't give a resolution. The below answer by @Niyoko Yuliawan helps.

Community
  • 1
  • 1
Elye
  • 53,639
  • 54
  • 212
  • 474
  • Change `func.inc` to `func.inc.php` and see what happens – RiggsFolly Nov 12 '16 at 05:18
  • And then there is [SCOPE, Scope, scope](http://php.net/manual/en/language.variables.scope.php) `$status_success;` is not visible inside the function – RiggsFolly Nov 12 '16 at 05:22
  • shall I, oh i already did –  Nov 12 '16 at 05:27
  • The pointed duplicate reference does explain about scope, but doesn't give the resolution to how to solve this. The below answer helps indeed. – Elye Nov 12 '16 at 06:28
  • Thanks @RiggsFolly, the references to http://php.net/manual/en/language.variables.scope.php helps. As a C and Java developer, this is puzzling that something declared globally are not taken into consideration in an inner function. Hence I ask this question puzzled. – Elye Nov 12 '16 at 06:37

2 Answers2

1

You need to declare $status_success variable as global variable.

function x($status){
    global $status_success;
    echo $status;
    echo $status_success;
}
Niyoko
  • 7,512
  • 4
  • 32
  • 59
  • Cool. That helps much! I upvote your answer and tick it, as it helps. I think my question is valid, as I can't really find a solution else where. Even the marked duplicate answer didn't tell me to put global. If you agree with me, perhaps you could help upvote my question back, as I don't think it deserved a negative vote. Thanks! – Elye Nov 12 '16 at 06:27
  • @Elye I upvoted your question, but it won't negate -2 downvotes as I can only upvote once. – Niyoko Nov 12 '16 at 14:30
  • Thanks @Niyoko Yuliawan. That's good enough. I think stackoverflow should enforce whoever down vote, should at least put a comment of reason why they down vote. – Elye Nov 13 '16 at 06:18
0

Turn the file name func.inc into func.inc.php so that PHP can parse that code. Also, don't forget to add <?php tags at the start to claiming that PHP script is going to start.

Benyi
  • 912
  • 2
  • 9
  • 24