سؤال

أعلم أنه في PHP يمكنك تضمين المتغيرات داخل المتغيرات، مثل:

<? $var1 = "I\'m including {$var2} in this variable.."; ?>

لكنني كنت أتساءل كيف، وإذا كان من الممكن تضمين دالة داخل متغير.أعلم أنني أستطيع أن أكتب فقط:

<?php
$var1 = "I\'m including ";
$var1 .= somefunc();
$var1 = " in this variable..";
?>

ولكن ماذا لو كان لدي متغير طويل للإخراج، ولا أريد القيام بذلك في كل مرة، أو أرغب في استخدام وظائف متعددة:

<?php
$var1 = <<<EOF
    <html lang="en">
        <head>
            <title>AAAHHHHH</title>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        </head>
        <body>
            There is <b>alot</b> of text and html here... but I want some <i>functions</i>!
            -somefunc() doesn't work
            -{somefunc()} doesn't work
            -$somefunc() and {$somefunc()} doesn't work of course because a function needs to be a string
            -more non-working: ${somefunc()}
        </body>
    </html>
EOF;
?>

أو أريد تغييرات ديناميكية في هذا التحميل من التعليمات البرمجية:

<?
function somefunc($stuff) {
    $output = "my bold text <b>{$stuff}</b>.";
    return $output;
}

$var1 = <<<EOF
    <html lang="en">
        <head>
            <title>AAAHHHHH</title>
            <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
        </head>
        <body>
            somefunc("is awesome!") 
            somefunc("is actually not so awesome..") 
            because somefunc("won\'t work due to my problem.")
        </body>
    </html>
EOF;
?>

حسنًا؟

هل كانت مفيدة؟

المحلول

يتم دعم استدعاءات الوظائف داخل السلاسل منذ PHP5 من خلال وجود متغير يحتوي على اسم الوظيفة المطلوب الاتصال بها:

<?
function somefunc($stuff)
{
    $output = "<b>{$stuff}</b>";
    return $output;
}
$somefunc='somefunc';
echo "foo {$somefunc("bar")} baz";
?>

سوف يخرج "foo <b>bar</b> baz".

أجد أنه من الأسهل (وهذا يعمل في PHP4) إما مجرد استدعاء الوظيفة خارج السلسلة:

<?
echo "foo " . somefunc("bar") . " baz";
?>

أو تعيين لمتغير مؤقت:

<?
$bar = somefunc("bar");
echo "foo {$bar} baz";
?>

نصائح أخرى

"bla bla bla".function("blub")." and on it goes"

التوسع قليلاً في ما قاله جيسون دبليو:

I find it easier however (and this works in PHP4) to either just call the 
function outside of the string:

<?
echo "foo " . somefunc("bar") . " baz";
?>

يمكنك أيضًا تضمين استدعاء الوظيفة هذا مباشرةً في ملف HTML الخاص بك، مثل:

<?

function get_date() {
    $date = `date`;
    return $date;
}

function page_title() {
    $title = "Today's date is: ". get_date() ."!";
    echo "$title";
}

function page_body() {
    $body = "Hello";
    $body = ",  World!";
    $body = "\n
\n"; $body = "Today is: " . get_date() . "\n"; } ?> <html> <head> <title><? page_title(); ?></title> </head> <body> <? page_body(); ?> </body> </html>
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top