Is it bad practice to echo out functions in php? - php

Is it bad practice to echo out a bunch of HTML using a function in php and having it something like this:
function my_function() {
global $post;
$custom_fields = get_post_custom();
$some_field = $custom_fields ['some_field'][0];
?>
<div class="something <?php if ($some_field) { echo $special-clas;} ?>">
<div class="something-else">
/* bunch more of html code */
</div>
</div>
}
And then in the page where you want to use that to echo it?
<html>
<body>
.....
....
<?php echo my_function(); ?>
....
I'm unsure how "accepted" it is to echo out functions?

Consider two functions:
function does_return() {
return 'foo';
}
function does_echo() {
echo 'bar';
}
does_return(); // nothing displayed
echo does_return(); // 'foo' displayed
does_echo(); // 'bar' displayed
echo does_echo(); // 'bar' displayed
In both cases, output CAN be performed, but how it happens differs. Since does_return() does not itself have ANY code to perform output within its definition, output is up to the calling code, e.g. the echo you perform.
With does_echo(), it doesn't matter how you call the function (with or without echo), since the function does the output itself. you'll get bar regardless.
Now consider this:
function this_is_fun();
echo 'foo';
return 'bar';
}
this_is_fun(); // outputs 'foo'
echo this_is_fun(); // outputs 'foobar';

This is bad practice, because it makes your code hard to maintain.
With a function like that you are mixing the logic and presentation. So, when you see something in your output that you don't like you can not be sure where to go first to go and change it. Do you go to the page code or the function code?

Functions are supposed to return data, and then your application deals with it how you wish, whether that’s assigning it to a variable or echoing it out.

I don't see how it's bad practice. As long as you're reusing the function, then it seems like you're using it the right way.
The only thing you shouldn't be doing is using global; rather pass $post to the function. See this answer for why.
Since your function already has an output, you don't need the echo.
my_function( $post );

That's fine. I'd rather see that than the PHP mixed in completely to the HTML.
You can use <?= my_function() ?> instead if you want to write a little less code.

What #DaveRandom said in his comment. Aside from that, no, it's not necessarily bad practice. It can though make for code that's hard to debug. Consider a MVC approach instead where the logic is largely in the Controller and the View simply handles rendering the view based on that logic.

Related

Render PHP HTML page from variable

Say I have a variable of a string that contains an html page. Within that html page variable I have an echo statement-
e.g. <?php echo 'whatever' ?>
Can I somehow "render" that variable to the browser, and have php evaluate all the php statements within the variable?
If I just echo the variable, the html renders fine but the php statements are not evaluated.
If I try running eval on the entire page, it just throws an exception (makes sense).
I know this all sounds like bad practice, but I'm trying to figure out a way to do this without saving the variable to a file and loading the file.
BTW: I'm doing this all within codeigniter, so if there's a way to use $this->load->view on that variable... that would be even better :)
Example Code:
$x = /* Some logic to get a template data from another server */
/* $x is "<html><?php echo 'bla'; ?></html> */
echo $x;
This doesn't work- trying to run echo eval($x) also doesn't work
You can write view data to variable and use this variable in other view
In you controller:
$data['view1'] = $this->load->view('my_view1', '', TRUE); // write view data to variable
$this->load->view('my_view2', $data);
In my_view2:
<html>
<?=$view1?>
</html>
This docs can help you Returning views as data - Codeigniter
I'm not sure I follow you, but I think this is what you want.
If page1_view.php contains HTML and needs to echo a variable. e.g.
<div>Foo says: <?php echo $whatever; ?>!!!</div>
To get that "view" as a string with the variable $whatever evaluated you need this.
$view_data['whatever'] = "Hello World";
$page1 = $this->load->view('page1_view', $view_data, TRUE);
$page1 now contains a string which is the contents of page1_view.php. in this case
"<div>Foo says: Hello World!!!</div>"

php functions playing games

I'm curious as to why variables aren't echoing using a function... (If that makes sense lol..)
function name(){
echo "$info->fullname";
}
When i then use
<?php name(); ?>
anywhere on withing the script, it's completely blank, yet if i remove the variable and put static text, it echo's out just fine...
It works fine without using it as a function, it echo's "Joe Bloggs"...
Not quite sure why it doesn't work ? lol
Any ideas guys?
yes MarkBaker is right. and you should use global. something like this.
function name(){
global $info;
echo $info->fullname;
}
or pass the variable to function like this.
function name($info){
global $info;
echo $info->fullname;
}
use
<?php name($info); ?>
and one advice which is not important at all : " is slower than ' try to use " only if needed.

repeat wordpress code

How do I set a piece of code to a function in WordPress and then call that function...this was my first guess, but of course this doesn't work...
Could someone suggest how I can get this to work so I can avoid redundant code. Also if I define code in a function can I call it in different .php files, or can I only call it within that file?
<?php
// This code will never change.
function $test {
echo('test this will be a long string and repeated many times.')
}
?>
<?php
echo $test;
?>
PHP function names (unlike variables) are declared without dollar signs:
function test (
To call a function, use this format:
test();
Your code example will look like this:
<?php
// This code will never change.
function test {
echo('test this will be a long string and repeated many times.')
}
?>
<?php
test();
?>

How to Display output from snippet without using echo

The documentation on snippets in modx: http://rtfm.modx.com/display/revolution20/Snippets
Near the top of the doc it says: Note how we returned the code rather than echo'ed the content out. Never use echo in a Snippet - always return the output.
This doesn't display anything:
return $product_attribute $product_info[0][$column_name];
This does display:
echo $product_attribute $product_info[0][$column_name];
If I can't echo the content how do I get it to print in the html page?
It basically means that you can echo the returned value rather than echo the value in the function itself. In OOP programming, echoing (or printing) to the screen is strictly monitored.
For example I have this function
function testExample($var) {
return $var*2;
}
So when I need to echo it, I just need to
echo testExample(5);
Instead of this (bad practice)
function testExample($var) {
echo $var*2;
}
The reason is that when you print value in the function, you can only use that function for printing the value, which isn't reusable at all. But by returning it, you can now use it for printing, or assigning to another variable or re-calculating on it.
From what I can understand from the note, there is a convention not to use echo inside a function, but rather return the value and perhaps echo it afterwards.
Other printing posibilities would be:
print $your_variable;
or die($your_variable);
return is used to return values from a function/method ect
The snippet functionality of modx is actually just a function/class wrapper.

PHP macro / inline functions (to avoid variables to go out of scope)

I have the following dilemma. I have a complex CMS, and this CMS is to be themed by a graphic designer. The templates are plain HTML, with several nested inclusions. I'd like to make it easier for the designer to locate the file to be modified, by looking at the HTML of the page.
What I thought in the first place was to build something stupid like this:
function customInclude($what) {
print("<!-- Including $what -->");
include($what);
print("<!-- End of $what -->");
}
but, guess what? Variables obviously come out of scope in the included file :-) I can't declare them as global or as parameters, as I don't know how they are called and how many are there.
Is there any possibility to implement some kind of "macro expansion" in PHP? An alternative way to call it: I'd like to modify each call of the modify function, in an aspect-oriented style.
I have thought about eval(), is it the only way? Will it have a big impact on performance?
I know this is an old question, but I stumbled upon it and it reminds me of something I used to do it too.
how about if you create the function using a very weird variable?
<?php
function customInclude($___what___) {
echo '<!-- Including '.$___what___.' -->';
include($what);
echo '<!-- End of '.$___what___.' -->';
}
?>
I usually suggest to add a possible variable to display those tags only when necessary, you do not want other people to know...
<?php
function __printIncludeInfo($info, $dump = false){
//print only if the URL contains the parameter ?pii
//You can modify it to print only if coming from a certain IP
if(isset($_GET['pii'])){
if($dump){
var_dump($info);
} else {
echo $info;
}
}
}
function customInclude($___what___) {
__printIncludeInfo('<!-- Including '.$___what___.' -->');
include($what);
__printIncludeInfo('<!-- End of '.$___what___.' -->');
}
?>
in this way you can use the function to print any other information that you need
Not sure if I entirely understand the question, but if you're just trying to make life easier for the designer by showing them the underlying filename of the included file, then you can probably just use this within the template files:
echo '<!-- Start of '.__FILE__.' -->';
....content...
echo '<!-- End of '.__FILE__.' -->';
__FILE__ is just one of several Magic Constants.
Also there's the get_included_files() function that returns an array of all the included files, which might be of use (you could output a list of all the included files with 'tpl' in their name for example).
This is my 100% harcoded solution to custom include problem. It's about using a global var to point the next include filename and then include my custom proxy-include-file (wich replace your custom proxy-include-function)
1 - Add this code to a global include (wherever your customInclude function is defined)
$GLOBALS['next_include'] = "";
$GLOBALS['next_include_is_once'] = false;
function next_include($include_file) {
$GLOBALS['next_include_is_once'] = false;
$GLOBALS['next_include'] = $include_file;
}
function next_include_once($include_file) {
$GLOBALS['next_include_is_once'] = true;
$GLOBALS['next_include'] = $include_file;
}
2 - Create some include proxy-include-file, by example "debug_include.php"
<?php
if(empty($GLOBALS['next_include'])) die("Includes Problem");
// Pre-include code
// ....
if($GLOBALS['next_include_is_once']) {
include_once($GLOBALS['next_include']);
} else {
include($GLOBALS['next_include']);
}
// Post-include code
// ....
$GLOBALS['next_include'] = "";
3 - Perform a search and replace in all your files: (except debug_include.php)
search: 'include((.*));' as a reg.exp
replace with: '{next_include($1);include('debug_include.php');}'
and
search: 'include_once((.*)); as a reg.exp
replace with: '{next_include_once($1);include('debug_include.php');}'
Maybe you should need another search-and-replaces if you have some non-standard includes like
include (.... include (.... include (....
I think you can find some better search-and-replace patterns, but I'm not a regular expression user so I did it the hard way.
You should definitely use objects, namespaces and MVC model. Otherwise there is no pure and clean solution to your problem. And please, don't use eval, it's evil.

Categories