Michael Irwin
Michael Irwin

Reputation: 3149

PHP lazy evaluation

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?

Upvotes: 0

Views: 1079

Answers (2)

slevy1
slevy1

Reputation: 3820

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.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173642

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>

Upvotes: 8

Related Questions