search
HomeBackend DevelopmentPHP TutorialVariable definition PHP variable definition and variable substitution methods

There are two ways to replace variables into strings - the simple way and the complex way.
The easy way is to put the variable name in a double quoted string or a heredoc:
$who = 'Kilroy';
$where = 'here';
echo "$who was $where";
Kilroy was here
Complex The method is to enclose the variable to be replaced in curly brackets. This approach can be used to disambiguate or replace array lookups. The classic function of braces is to separate the variable name from the surrounding text:
$n = 12;
echo “You are the {$n}th person”;
You are the 12th person
If there are no braces, PHP will try to print out the value of the variable $nth.
Unlike some shell environments, variables in PHP strings will not be parsed repeatedly, but will only be parsed in double-quoted strings, and the result will be used as the value of the string:
$bar = 'this is not printed ';
$foo = '$bar'; // Single quotes
print("$foo"); // Double quotes
$bar
4.1.2 Strings enclosed in single quotes
Single-Quoted Strings
Use Strings enclosed in single quotes do not replace variables. Because string literals are enclosed in single quotes, variable names are not parsed in the following string:
$name = 'Fred';
$str = 'Hello, $name'; // single-quoted Enclosed in single quotes
echo $str;
Hello, $name
The only escape sequence available in a string enclosed in single quotes is ' (putting single quotes inside a string enclosed in single quotes) , \ (putting a backslash inside a string enclosed in single quotes). Any other backslash will only be interpreted as a backslash:
$name = 'Tim O'Reilly'; //Escaped single quote
echo $name;
$path = 'C:\WINDOWS'; //Escaped backslash
echo $path;
$nope = 'n'; // Not an escape sequence
echo $nope;
Tim O'Reilly
C:WINDOWS
n
4.1.3 Use double quotes Surrounded Strings
Double-Quoted Strings
Strings enclosed in double quotes will be variable parsed and many escape sequences are allowed. Table 4-1 lists the escape sequences that PHP recognizes in strings enclosed in double quotes.
Table 4-1: Escape sequences in strings enclosed in double quotes
Escape sequence character meaning

Double quotes
n
Line feed
r
Carriage return
t
Tab character
\
Backslash Bar
$
Dollar sign
{
Left brace
}
Right brace
[
Left bracket
]
Right bracket
If you use a heredoc in a more complex expression, you need to write the expression on separate lines:
printf(%s is %d years old.
Template
, “Fred”, 35 );
Single and double quotes in the heredoc are skipped (treated as normal symbols):
$dialogue = "It's not going to happen!" she fumed.
He raised an eyebrow. "Want to bet?"
No_More;
echo $dialogue;
"It's not going to happen!" she fumed.
He raised an eyebrow. "Want to bet?"
Whitespace in the heredoc is also preserved :
$ws = boo
hoo
Enough;
// $ws = ” boon hoon”;
Because the newline character before the end terminator will be removed, the following two The assignment is the same:
$s = 'Foo';
// same as
$s = Foo
End_of_pointless_heredoc;
If you want to end the heredoc reference with a newline character String, you need to add it yourself:
$s = Foo
End;
//Note that Foo is followed by a blank line and cannot be deleted

The above introduces the methods of variable definition, PHP variable definition and variable substitution, including the content of variable definition. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the best way to send an email using PHP?What is the best way to send an email using PHP?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

Best Practices for Dependency Injection in PHPBest Practices for Dependency Injection in PHPMay 08, 2025 am 12:21 AM

The reason for using Dependency Injection (DI) is that it promotes loose coupling, testability, and maintainability of the code. 1) Use constructor to inject dependencies, 2) Avoid using service locators, 3) Use dependency injection containers to manage dependencies, 4) Improve testability through injecting dependencies, 5) Avoid over-injection dependencies, 6) Consider the impact of DI on performance.

PHP performance tuning tips and tricksPHP performance tuning tips and tricksMay 08, 2025 am 12:20 AM

PHPperformancetuningiscrucialbecauseitenhancesspeedandefficiency,whicharevitalforwebapplications.1)CachingwithAPCureducesdatabaseloadandimprovesresponsetimes.2)Optimizingdatabasequeriesbyselectingnecessarycolumnsandusingindexingspeedsupdataretrieval.

PHP Email Security: Best Practices for Sending EmailsPHP Email Security: Best Practices for Sending EmailsMay 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

How do you optimize PHP applications for performance?How do you optimize PHP applications for performance?May 08, 2025 am 12:08 AM

TooptimizePHPapplicationsforperformance,usecaching,databaseoptimization,opcodecaching,andserverconfiguration.1)ImplementcachingwithAPCutoreducedatafetchtimes.2)Optimizedatabasesbyindexing,balancingreadandwriteoperations.3)EnableOPcachetoavoidrecompil

What is dependency injection in PHP?What is dependency injection in PHP?May 07, 2025 pm 03:09 PM

DependencyinjectioninPHPisadesignpatternthatenhancesflexibility,testability,andmaintainabilitybyprovidingexternaldependenciestoclasses.Itallowsforloosecoupling,easiertestingthroughmocking,andmodulardesign,butrequirescarefulstructuringtoavoidover-inje

Best PHP Performance Optimization TechniquesBest PHP Performance Optimization TechniquesMay 07, 2025 pm 03:05 PM

PHP performance optimization can be achieved through the following steps: 1) use require_once or include_once on the top of the script to reduce the number of file loads; 2) use preprocessing statements and batch processing to reduce the number of database queries; 3) configure OPcache for opcode cache; 4) enable and configure PHP-FPM optimization process management; 5) use CDN to distribute static resources; 6) use Xdebug or Blackfire for code performance analysis; 7) select efficient data structures such as arrays; 8) write modular code for optimization execution.

PHP Performance Optimization: Using Opcode CachingPHP Performance Optimization: Using Opcode CachingMay 07, 2025 pm 02:49 PM

OpcodecachingsignificantlyimprovesPHPperformancebycachingcompiledcode,reducingserverloadandresponsetimes.1)ItstorescompiledPHPcodeinmemory,bypassingparsingandcompiling.2)UseOPcachebysettingparametersinphp.ini,likememoryconsumptionandscriptlimits.3)Ad

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.