简体   繁体   中英

Dynamic Link Creation with PHP

I have a whole bunch of repetitive link creation code ( <a href ). I would like to create a function to call this block of code based on a list of different variables.

The links are inside a table. I have about 15 links almost identical to the one below (the only difference being the Make which in this example is 'FORD') :

Here is the slab of code which is repeated:

<td>
  <a href="<?php echo PopulateModel($CategoryId, 1); ?>">
    <img src="images/brands/ford.gif" title="Click here if you have a Ford"> 
  </a>
  <center>
    <a href="<?php echo PopulateModel($CategoryId, 1); ?>" class="make">FORD</a>
  </center>
</td>

The Function I want to create is to receive an array of different Models of vehicles, and I want to create a link for each.

I tried using the HEREDOC function in PHP to echo the slab of code via a function but that didn't seem to work. The PHP tags inside of an echo statement seem to be giving errors.

Here is my HEREDOC code (which doesn't work):

function CreateBrandLink($brand_name){
echo <<<EOT
<td><a href="<?php echo PopulateModel($CategoryId, 1); ?>"><img src="images/brands/ford.gif" title="Click here if you have a Ford"></a>
<center><a href="<?php echo PopulateModel($CategoryId, 1); ?>" class="make">FORD</a></center></td>
</td>
EOT;
}
function CreateBrandLink($brand_name){
   $b = PopulateModel('a', 1);
   $r = <<<EOT
   <td>
    <a href="$b">
     <img src="images/brands/ford.gif" title="Click here if you have a Ford">
    </a>
    <center>
     <a href="$b" class="make">FORD</a>
    </center>
   </td>
EOT;
return $r;
}

You cannot place <?php blocks inside a HEREDOC. So let's fix that first...

function CreateBrandLink($brand_name){
    $href = PopulateModel($CategoryId, 1);
    echo <<<EOT
<td><a href="{$href}"><img src="images/brands/ford.gif" title="Click here if you have a Ford"></a>
<center><a href="{$href}" class="make">FORD</a></center></td>
</td>
EOT;
}

Now this still won't work because you're referencing $CategoryId when you call PopulateModel() when in fact the only parameter your function has is $brand_name .

I don't know your code well enough to know how to correct that, but at least we've fixed the syntax problem.

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