简体   繁体   中英

PHP pass variable to include from the include call

Is it possible to pass a variable to an include, at the include call, and then use that variable in the include file?

eg something like this:

// include this somewhere
<?php include 'includes/contact_form.php', $platform='desktop' ?>

// and this somewhere else 
<?php include 'includes/contact_form.php', $platform='mobile' ?>

// then inside the contact_form.php file use them like

<input id="name_<?echo $platform ?>" type="text">
<input id="email_<?echo $platform ?>" type="email">

// which would result in:
<input id="name_desktop" type="text">
<input id="email_desktop" type="email">

// and 
<input id="name_mobile" type="text">
<input id="email_mobile" type="email">

You can define a platform variable before the include and the included file will have access to it:

index.php

<?php
    $platform = 'desktop';
    include 'contact_form.php'; 
?>

contact_form.php

Platform is: <?php echo $platform; ?>

<input id="name_<?php echo $platform; ?>" type="text">
<input id="email<?php echo $platform; ?>" type="email">

// EDIT

Since you specifically mentioned "at the include call" I thought I would mention that it could be possible to do:

include 'http://example.com/contact_form.php?platform=desktop'

But if you wanted to dynamically change the platform you'd still need (1) to define a platform variable and (2) using this remote format requires allow_url_include enabled. You can read more about this at the manual page for include .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM