在php中替换的正确语法?
初学者问题 如何替换:在php中替换的正确语法?,php,Php,初学者问题 如何替换: $\u会话['personID']用于{personID},如下所示: public static $people_address = "/v1/People/{personID}/Addresses" 看看这个: $template = "/v1/People/{personID}/Addresses"; $people_address = str_replace('{personID}', $_SESSION['personID'], $template); ec
$\u会话['personID']
用于{personID}
,如下所示:
public static $people_address = "/v1/People/{personID}/Addresses"
看看这个:
$template = "/v1/People/{personID}/Addresses";
$people_address = str_replace('{personID}', $_SESSION['personID'], $template);
echo $people_address;
输出:
/v1/People/someID/Addresses
看看这个:
$template = "/v1/People/{personID}/Addresses";
$people_address = str_replace('{personID}', $_SESSION['personID'], $template);
echo $people_address;
输出:
/v1/People/someID/Addresses
编辑:编辑后,此答案不再适用于该问题,但我将其保留一段时间,以解释评论中出现的一些问题此问题的另一个答案 有几种方法,
操作符可能是最容易理解的,它的全部目的是连接字符串
public static $people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
//PHP Parse error: syntax error, unexpected '.', expecting ',' or ';'
public static $people_address = "/v1/People/$_SESSION[personID]/Addresses";
//PHP Parse error: syntax error, unexpected '"' in
但是,您不能在属性声明中使用连接,只能使用简单的赋值。您也不能使用“字符串替换”格式:
为了解决这个问题,您可以在类之外分配静态变量,即:
class test {
public static $people_address;
// ....
}
// to illustrate how to work around the parse errors - and show the curly braces format
test::$people_address = "/v1/People/${_SESSION[personID]}/Addresses";
// another (much better) option:
class test2 {
public static $people_address;
public static function setup() {
self::$people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
}
}
// somewhere later:
test2::setup();
编辑:编辑后,此答案不再适用于该问题,但我将其保留一段时间,以解释评论中出现的一些问题此问题的另一个答案 有几种方法,
操作符可能是最容易理解的,它的全部目的是连接字符串
public static $people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
//PHP Parse error: syntax error, unexpected '.', expecting ',' or ';'
public static $people_address = "/v1/People/$_SESSION[personID]/Addresses";
//PHP Parse error: syntax error, unexpected '"' in
但是,您不能在属性声明中使用连接,只能使用简单的赋值。您也不能使用“字符串替换”格式:
为了解决这个问题,您可以在类之外分配静态变量,即:
class test {
public static $people_address;
// ....
}
// to illustrate how to work around the parse errors - and show the curly braces format
test::$people_address = "/v1/People/${_SESSION[personID]}/Addresses";
// another (much better) option:
class test2 {
public static $people_address;
public static function setup() {
self::$people_address = "/v1/People/".$_SESSION['personID']."/Addresses";
}
}
// somewhere later:
test2::setup();
标题是连接,问题状态替换(如str_替换),你在找哪一个?抱歉,可能替换在标题中会更好。标题是连接,问题状态替换(如str_替换),你在找哪一个?抱歉,可能替换在标题中会更好。