Kirk Ross
Kirk Ross

Reputation: 7163

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?

e.g. 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">

Upvotes: 1

Views: 210

Answers (1)

Juan V
Juan V

Reputation: 508

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.

Upvotes: 4

Related Questions