0

For some reason my PHP function call <? r(); ?> returns a fatal error. Any help?

<?php
//$r is previously assigned
function r() {
    echo ( $r );
};
?>

<html>
    <head>
        <link type="text/css" rel="stylesheet" href="<? r(); ?>rs/css/master.css">
    </head>
2
  • 2
    Posting the error message might be helpful Commented Mar 2, 2012 at 0:37
  • 1
    Unless something is turning an E_NOTICE into an Exception, what you've describe isn't sufficient to generate a fatal error. Please post more information about the error you're experiencing. Commented Mar 2, 2012 at 0:42

2 Answers 2

4

Defining a function changes the scope, where $r won't be inside that function. Try sending in $r with the function in this manner:

<?php
function r($r) {
    echo ( $r );
}
?>
<link type="text/css" rel="stylesheet" href="<?php r($r); ?>rs/css/master.css">

or defining global $r; at the beginning of the function (not preferred).

Also, you shouldn't use <? to open PHP. If all the function does is echo the value of $r, it would make more sense to just do this:

<link type="text/css" rel="stylesheet" href="<?php echo ( $r ); ?>rs/css/master.css">
Sign up to request clarification or add additional context in comments.

3 Comments

Agreed...except for defining $r as global. ;-)
@Nilpo: I don't like using global for a simple variable, which is why I more mentioned it as a side-note afterwards. I used my ninja-powers to utilize my grace period and make it smaller. ;)
Right on. I definitely agree with you. Using global variables is almost always a bad practice. Variables should be explicitly passed between scopes. Less mistakes, neater code that easier to follow, etc. I won't say definitively say they don't have their place, but I can only think of a single time I would condone using globals--when defining globally accessible constants. But even then, I personally resort to other means.
1

If you want to refer to a global object from inside an object, you need to explicitly declare it as global:

function r() {
    global $r;
    echo ( $r );
}

But in general, referring to global variables in this way is bad style. You should consider passing in prerequisites as function arguments:

function r($r) {
     echo ( $r );
}

...

r($r);

1 Comment

bad style still gets the job done and keeps the code short. props

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.