PHP,變數裡帶有變數

來源:互聯網
上載者:User
PHP,變數裡含有變數!
$mcontent 的內容是“ dear:{$user['username']} 你購買的商品:{$goods_name},訂單號{$goods_no}已下單成功,由於此商品近期銷售火爆,請及時付款! ”


其中裡面的也是變數,可以我 echo $mcontent; 輸不出裡的變數,請問大神要怎麼做!!! php 變數

分享到:


------解決方案--------------------
//類比從資料庫中讀出的資料
$mcontent =<<< 'TXT'
dear:{$user['username']}
你購買的商品:{$goods_name},訂單號{$goods_no}已下單成功,由於此商品近期銷售火爆,請及時付款!
TXT;

//涉及的變數需自行保證存在
$user['username'] = 'body';
$goods_name = 'xxx';
$goods_no = '123';

//方案一 不過有不少人恐懼 eval
$mcontent = eval("return \"$mcontent\";");
echo $mcontent;

//方案二 動態建立函數,格式有點繞人
$f = create_function('$user,$goods_name,$goods_no', "return \"$mcontent\";");
$mcontent = $f($user, $goods_name, $goods_no);
echo $mcontent;
//或
$f = create_function('$user,$goods_name,$goods_no', 'return "' . $mcontent . '";');
$mcontent = $f($user, $goods_name, $goods_no);
echo $mcontent;

//方案三 模板變數替換,這是解釋型模板引擎的做法
$mcontent = preg_replace('/{\$[^}]+}/e', '$1', $mcontent);
echo $mcontent;
均將得到:
dear:body
你購買的商品:xxx,訂單號123已下單成功,由於此商品近期銷售火爆,請及時付款!
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.