Jump to content

[SOLVED] variable scope


mxl

Recommended Posts

I'm new to PHP.  I have a simple, but frustrating problem.  Scope of variables...

 

I'm creating .php files as external header and footer files.  Yet, I'd like control from the calling page to "pass" the contents of, for instance the $title, $description and $keywords to the appropriate line of code in the appropriate "require_once" files.

 

What am I doing wrong?  Am I required pass variables using a function, or can I just use the contents of the variable defined on the calling page in the "require_once page?

 

mxl

Link to comment
https://forums.phpfreaks.com/topic/122783-solved-variable-scope/
Share on other sites

Thanks,

 

I just put a page together outside of my environment, and it worked. 

 

One more question.  If I've got a ton of HTML and want to add variable contents into the code using the following example, how can I delimit the HTML from the PHP best?  What is the convention?

 

$myVar = "Some Variable";

 

<body>

<p>Here is some text. then I want to show a variable: .$myVar. and make sure that my text continues...</p>

</body>

 

Marcus

You have tons of choices.  You could do:

 

1) End the PHP block and then restart it after the HTML:

<?php
$test = "some text goes here";
?>
<p>What goes here...?  Oh yeah, <?php echo $test; ?>!  And here, too.</p>

 

2) Just make a string and echo it:

<?php
$test = "some text goes here";
echo "<p>What goes here...? Oh yeah, $test!  And here, too.</p>";
?>

 

3) Use a templating system:

PHP File:

<?php
$template = new Smarty();  //assume you have this all set up
$test = "some text goes here";
$template->assign('test', $test);
$template->display('sample.tpl');
?>

 

sample.tpl

<p>What goes here...?  Oh yeah. {$test}!  And here, too.</p>

 

I'd only suggest templating for big projects.

Thank you, DarkWater.  I like your example 2 very much.  Now, I know that I'm going to have a ton of Escaped characters in my text including entire URLs, etc.  I'd like to avoid escape sequencing every character. 

 

Is there some way that I can just use the $some text inline where I need to, yet, leave all of the HTML intact?

 

mxl

That's one of the big "problems" with echoing HTML.  The attributes all have quotations, which can make it tricky.  I personally like the printf() function:  (along with sprintf(), but that has other uses)

 

<?php
$test = "some text goes here";
printf('<p class="some-class">I'd normally need escapes and all sorts of stuff, but now I don't so I can let you know that %s.', $test);
?>

 

Look at the manual page for printf().  If you happen to program in C, it's the same function.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.