Reputation: 13
Similar questions have been posted but I have not been able to find an answer.
This IF statement works correctly by it's self.
$subject_id_top = "case studies";
if($subject_id_top == "case studies") {echo "active";}
But when I inserted this IF statement inside a function it does not work.
<style>
.active {
color:#F00;
}
</style>
<?php
$subject_id_top = "case studies";
function menu_active() {
if($subject_id_top == "case studies") {echo "active";}
}
<a class="<?php menu_active(); ?>" href="#">Case Studies</a>
?>
This seems to be a very basic issue but for the life of me I havent been able to figure it out. The community help will be great. Thanks in advance.
Upvotes: 0
Views: 92
Reputation: 22783
Because $subject_id_top
inside the function refers to $subject_id_top
outside the scope of the function (the global scope), you have to 'import' it, so to speak, with the statement:
global $subject_id_top;
You're function should then become:
function menu_active() {
global $subject_id_top;
if($subject_id_top == "case studies") {echo "active";}
}
However, relying on information from outside scopes, in this way, is usually not preferable. You could refactor your function to accept an argument to circumvent this behavior, like so, for instance:
function menu_active( $subject_id_top ) {
if($subject_id_top == "case studies") {echo "active";}
}
And then call that function with $subject_id_top
, from the global scope, as its argument:
<?php menu_active( $subject_id_top ); ?>
Upvotes: 1