Last active
January 30, 2017 05:25
-
-
Save mishterk/15f1813526cc5f7f9f867eb82b2fffd1 to your computer and use it in GitHub Desktop.
A quick example of interpolation in PHP (for Ben)...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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