How to Display output from snippet without using echo - php

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.

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>"

rest echo vs return in GET

I am a newbie in php and rest and I'm trying to understand what is going on in my API when using echo vs return....
I've tried to get down to the simplest possible scenario to isolate an issue of my rest API not returning any value, so here is goes:
I have a test.php file on my server with following content:
<?php
if(function_exists($_GET['t1'])) {
echo $_GET['t1']();
}
else if(function_exists($_GET['t2'])) {
return $_GET['t2']();
}
function test() {
return json_encode("test...");
}
?>
I then make a simple request using, as unique header 'Content-Type: application/json`
https://www.eswys.ch/tmp/test.php?t1=test
https://www.eswys.ch/tmp/test.php?t2=test
And results are, respectively
"test..."
""
I really struggle to understand this, why is my returned value somehow "lost" - is there any explanation to this?!
Returning from a function does not actually render any content to the response. You may have seen people returning data in different frameworks but the framework is actually echoing the data for you behind the scenes.
return assigns a value to a function call (like a variable) and echo is simply output to the html page or possibly a terminal window.

Best way to determine if a function has an output?

I have a list of functions that runs a fairly deep routine to determine which post_id to get its content from and output it on the site's frontend.
When this function returns its content I want it to be wrapped in an html wrapper. I want this html wrapper to only load if the function has an output to return.
In example, I have the following...
public static function output_*() {
// my routines that check for content to output precede here
// if there IS content to output the output will end in echo $output;
// if there is NO content to output the output will end in return;
}
In full explanation, I have the following...
If one of these functions returns an output I want it to be wrapped in an html wrapper, so in theory something like this is what I am trying to accomplish...
public static function begin_header_wrapper() {
// This only returns true if an output function below returns content,
// which for me is other than an empty return;
include(self::$begin_header_wrapper);
}
public static function output_above_header() {
// my routines that check for content to output precede here
// if there is content to return it will end in the following statement
// otherwise it will end in return;
include($begin_markup); // This is the BEGIN html wrapper for this specifc output
// It is, so let's get this option's post id number, extract its content,
// run any needed filters and output our user's selected content
$selected_content = get_post($this_option);
$extracted_content = kc_raw_content($selected_content);
$content = kc_do_shortcode($extracted_content);
echo $content;
include($end_markup); // This is the END html wrapper for this specifc output
}
public static function output_header() {
// the same routine as above but for the header output
}
public static function output_below_header() {
// the same routine as above but for the below header output
}
public static function end_header_wrapper() {
// This only returns true if an output function above returns content,
// which for me is other than an empty return;
include(self::$end_header_wrapper);
}
I know right now, ahead of time I don't want to determine twice (once in the start and once at the end) if one of the output functions has an output, when there should be a way to do this with one check, but I would like to get started down this rabbit hole and figure out the best way to determine if my function is returning something or not.
Or if there is an entirely better way to approach this please go all out, lol and let me know.
I looked online at this article and others
# Find out if function has any output with php
So in the end, I just wanted to know if there is a better way to approach this and what is actually the BEST way you think to check if my functions have an output to return so I can run my html wrapper based on those conditions?
Would ob_get_length be the best way? As I looked over the ob purposes, this one seemed best, and most simplistic, but wanted to get some advice, feedback. Or maybe I can check if my variable $content is returned? Thanks. Really appreciate it!
You can catch the result and store it in a variable, which is then given to the empty() function.
if(!empty(($output = yourFunctionToTest(param1, paramN)))) {
// do something with $output (in this case there is some output
// which isn't considered "empty"
}
This executes your function, stores the output in a variable ($output in this case) and executes empty() to check the variables content.
You are able to use the content of $output afterwards.
Be aware that empty() consideres empty strings or 0 as "empty", therefore returning true.
As an alternative you may use functions like isset() to determine if a variable is not null.
http://php.net/isset
http://php.net/empty

Is it bad practice to echo out functions in 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.

PHP echo only if another PHP reference exists?

Not sure if this is possible but what I am wanting to do is echo a html text link only if the page contains certain php code, in particular just the opening reference of 'myApi'. So if the page contains the following code:
<?php myAPI(variables); ?>
Then I would like to include this somewhere else on the page
<?php echo 'Click Here'; ?>
Any help would be much appreciated, thanks :)
Set an if somewhere, and use isset to test if your API has set a specific variable or not.
if(isset($apiVariable)) {
echo "link content...";
}
(The variable should be specific to your API, obviously.)
Update
I said "somewhere", but it's probably best to do the test logic it in a separate place than where you output the HTML. In that case, you'd need a flag for when you're ready to spit out the HTML:
isset($apiVariable) ? $apiFlag = true : $apiFlag = false;
// continue other PHP operations...
//...now your logic is finished, output HTML.
if($apiFlag) { echo "<a>Link</a>"; }
That way, when you re-visit the page later for revision or update, your logic not all mixed up with your display.
<?php if (isset($variable)): ?>
Click Here
<?php endif; ?>
The function isset() check if the variable is set and returns a boolean. so you can use it to check if a variable exist.

Categories