Skip to content

Instantly share code, notes, and snippets.

@mishterk
Last active January 30, 2017 05:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mishterk/15f1813526cc5f7f9f867eb82b2fffd1 to your computer and use it in GitHub Desktop.
Save mishterk/15f1813526cc5f7f9f867eb82b2fffd1 to your computer and use it in GitHub Desktop.
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