Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A quick example of interpolation in PHP (for Ben)...
<?php
// Quick PHP interpolation example...
class Person {
public $name = '';
public function getName()
{
return $this->name;
}
}
$name = 'Ben';
$person = new Person();
$person->name = $name;
// We can use the normal concatenation operator...
echo 'Do you know ' . $name . '? He has a face.' . "\r\n";
// >> Do you know Ben? He has a face.
// OR we can use double quotes and drop the variable right
// into the string. This is interpolation...
echo "Do you know $name? He has a face.\r\n";
// >> Do you know Ben? He has a face.
// If PHP has trouble discerning the variable from the string,
// we can wrap the variable in curly braces...
echo "Do you know {$name}? He has a face.\r\n";
// >> Do you know Ben? He has a face.
// We can also use object properties directly in the string...
echo "Do you know $person->name? He has a face.\r\n";
// >> Do you know Ben? He has a face.
// Notice we can't use an object method without wrapping it
// in curly braces...
echo "Do you know $person->getName()? He has a face.\r\n";
// >> Do you know ()? He has a face.
echo "Do you know {$person->getName()}? He has a face.\r\n";
// >> Do you know Ben? He has a face.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.