0

I'm trying to do lazy variable evaluation using PHP. Contrived example code:

<?php

function title($page)
{
    return $page . ' - $_GET["title"]';
}

?>


<title><?= title($_SERVER['SCRIPT_NAME']) ?></title>

$_GET['title'] isn't being evaluated. How can I achieve this?

0

2 Answers 2

8

Variable references inside single quotes aren't evaluated, according to the documentation. Use double quotes or simple concatenation:

function title($page)
{
    return $page . ' - ' . $_GET["title"];
}

And you should always properly escape variables when used in HTML, using htmlspecialchars().

<title><?= htmlspecialchars(title($_SERVER['SCRIPT_NAME'])); ?></title>
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. I'm fully aware of the double vs. single qoute interpolation rules. I'm just trying to get the $_GET var to be "lazy" evaluated.
what is "lazy" evaluated ?
@MichaelIrwin, if you're "fully aware" of how single quotes work, it sounds like you chose to use them on purpose. It's unclear what you mean by "lazy evaluation" if it doesn't mean waiting for the function to be called before accessing $_GET, and it's also unclear why you think single quotes will help.
I was just about to suggest (in a comment above) using return $page . ' - ' . $_GET["title"]; - Plus, assuming OP has short open tags ON.
@Fred-ii- Yes, or >= 5.4 is used.
|
1

Here's one way you could do some lazy evaluation:

<?php

$_GET["title"] = "";  // faking a GET with a missing title

function title($page)
{
    $title = htmlentities($_GET["title"]);
    return $page . ' - ' .  ($title = $title?: 'missing title');
}

echo title( htmlentities( $_SERVER['SCRIPT_NAME'] ) );
?>

If there's any kind of a title it will display but if it's missing, then user gets notified. I make use of the '?:' operator which assures that $title gets assigned the value of the right-hand operand, if $title holds a false value. Note, generally PHP does not make use of lazy evaluation outside of working with Booleans and the logical as well as bit-wise operators. Altho' there is the odd case of passing an argument when attempting to instantiate a class that lacks a constructor in which case while an opcode gets generated pertaining to that argument, it never executes and so the expression never evaluates.

Comments

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.