Yii2: Global variable in view - php

I'm need to concatenate lines for later output (markdown processing...). This is why I use a function l() and a global variable $content.
My view code:
$content = "";
function l($line="") {
global $content;
$content .= $line."\n";
}
l("hello");
echo "+";
echo $content;
echo "-";
outputs
+-
I'd expect:
+Hello-
Why? What am I doing wrong?
I am using PHP 7.2.6
EDIT:
There are several PHP related answers as this one. But they don't help. I suppose the problem is related to Yii2 and more specific to Yii2 view handling.

Found the solution! Crazy!
Yii2 renders the view inside an object instance.
This means, the PHP variable declaration
$content = "";
is not global but local to the rendering context.
The solution for question is to make the variable declaration in the view global, too:
global $content = "";
The working code inside the view looks like this now:
global $content = "";
function l($line="") {
global $content;
$content .= $line."\n";
}
l("hello");
echo "+";
echo $content;
echo "-";
Bingo!

Related

Echo / printr inside variable

I have inside a php file a variable called $html which is gathering lots of information like this:
$html .= something;
$html .= something else;
etc
and in another file its being echoed like this:
echo $this->html;
What i need is at first file that $html .= is used to echo something like this:
echo '<pre>';
echo 'printr($this->cart)';
echo '</pre>';
But i need those 3 lines to be included in $html variable in order to be echoed at second file through: echo $this->html;
Any ideas?
Thank you in advance
use var_export() function for including your array in to $html variable
In php file just assign what you want to assign to $html variable then you can print it anywhere by it's variable name .
for example :
$html="";
$html .="your text";
$html .="any dynamic values";
then echo this like
echo $html;
if you are using function then simply call a function and pass your all code within function then called function from anywhere.

php best practices for returning multiple lines of content in an IF statement

I am writing a php plugin for wordpress. I'm trying to be mindful of clean coding and want to know the best practice for returning several lines of HTML code in an IF statement.
Obviously I know about echo but I thought I had seen a technique like this used, but it doesn't seem to work for me. The idea being that you create several $content variables and then return it outside of the IF statement.
function signup() {
if(!Skizzar_Registration::is_skizzar_site_active()) {
$content = '<div class="signup">';
$content .= '<h1>Sign up</h1>';
$content .= '</div>';
} else {
$content = '<div class="signed_up">you are already signed up</div>';
}
return $content;
}
Currently though this returns nothing when I call the function
As you have already discovered, the specific issue is that you are not ecxhoing the data.
As per your followon question (which is prefered, return or echo), in wordpress there seems to be a convention where both options are offered with the functions named accordingly:
//echos
function the_signup_form(){
echo get_the_signup_form();
}
//returns
function get_the_signup_form(){
if(!Skizzar_Registration::is_skizzar_site_active()) {
$content = '<div class="signup">';
$content .= '<h1>Sign up</h1>';
$content .= '</div>';
} else {
$content = '<div class="signed_up">you are already signed up</div>';
}
return $content;
}

PHP include HTML and echo out variable

I am working on a script with templates. So I have this PHP code:
<?php
$string = "TEST";
echo(file_get_contents('themes/default/test.html'));
?>
And I have this HTML (the test.html file):
<html>
<p>{$string}</p>
</html>
How can I make PHP actually display the variable inside the curly brackets? At the moment it displays {$string}.
P.S:
The string might also be an object with many many variables, and I will display them like that: {$object->variable}.
P.S 2: The HTML must stay as it is. This works:
$string = "I'm working!"
echo("The string is {$string}");
I need to use the same principle to display the value.
You can use the following code to achieve the desired result:
<?php
$string = "TEST";
$doc = file_get_contents('themes/default/test.html'));
echo preg_replace('/\{([A-Z]+)\}/', "$$1", $doc);
?>
P.S. Please note that it will assume that every string wrapped in { }
has a variable defined. So No error checking is implemented in the code above. furthermore it assumes that all variables have only alpha characters.
If it is possible to save your replacees in an array instead of normal variables you could use code below. I'm using it with a similar use case.
function loadFile($path) {
$vars = array();
$vars['string'] = "value";
$patterns = array_map("maskPattern", array_keys($vars));
$result = str_replace($patterns, $vars, file_get_contents($path));
return $result;
}
function maskPattern($value) {
return "{$" . $value . "}";
}
All you PHP must be in a <?php ?> block like this:
<html>
<p><?php echo "{" . $string . "}";?></p>
</html>
If you know the variable to replace in the html you can use the PHP function 'str_replace'. For your script,
$string = "TEST";
$content = file_get_contents('test.html');
$content = str_replace('{$string}', $string, $content);
echo($content);
It's simple to use echo.
<html>
<p>{<?php echo $string;?>}</p>
</html>
UPDATE 1:
After reading so many comments, found a solution, try this:
$string = "TEST";
$template = file_get_contents('themes/default/test.html', FILE_USE_INCLUDE_PATH);
$page = str_replace('{$string}',$string,$template);
echo $page;

Plugin content always on top of post WordPress

I'm trying to make a WordPress plugin. Well, actually it's done and fully working, except one thing.
I have added a shortcode for the plugin. But no matter where in the content I call this shortcode, the contents it gets are always on top of the post, instead of where I placed the tag.
The code that outputs something:
public static function showIncomingSearches(){
global $id;
$arSearches = self::getArObj(array('wp_post_id' => $id));
ob_start();
if(!empty($arSearches)){
$str = '<ul>' . PHP_EOL;
foreach($arSearches as $oSearch){
$str .= '<li>'.htmlspecialchars($oSearch->searchterm).'</li>' . PHP_EOL;
}
$str .= '</ul>';
if(!empty($arSearches))
echo $str;
} else {
echo ' ';
}
return ob_get_clean();
}
And the shortcode functionality:
add_shortcode('show_incoming_searches', 'checkReferrer');
function checkReferrer(){
incomingSearches::checkReferrer();
echo incomingSearches::showIncomingSearches();
}
What I want to know though, is why it is always on top of the content?
Your shortcode code needs to return the content, not echo it.
function checkReferrer(){
incomingSearches::checkReferrer();
return incomingSearches::showIncomingSearches();
}

PHP include inside of a variable

I have a function that is controlling the output of my page:
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class='media-desc'>{$desc}</div>";
I would like to include a file "box.php" inside that html that is defined in the $page variable. I tried this:
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . include("box.php"); . "</div><div class='media-desc'>{$desc}</div>";
... but it didn't work. How can I put a php include inside of a variable?
from php.net
// put this somewhere in your main file, outside the
// current function that contains $page
function get_include_contents($filename) {
if (is_file($filename)) {
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
return false;
}
// put this inside your current function
$string = get_include_contents('box.php');
$page = '<div class="media-title"><h2>{$title}</h2></div>';
$page .= '<div class="media-image">{$image}</div>';
$page .= '<div class="inlinebox">' . $string . '</div>';
$page .= '<div class="media-desc">{$desc}</div>';
How can I put a php include inside of a variable?
# hello.php
<?php
return "Hello, World!";
?>
# file.php
$var = include('hello.php');
echo $var;
I would generally avoid such a thing though.
First, don't use a semicolon from inside the statement.
Second, wrap the include statement in parentheses.
$page = "<div class='media-title'><h2>{$title}</h2></div>
<div class='media-image'>{$image}</div><div class="inlinebox">" .
(include "box.php") . "</div><div class='media-desc'>{$desc}</div>";
Finally: In the "box.php" file, you will need to do the following:
<?php
ob_start();
// your code goes here
return ob_get_clean();
EDIT: Some info about calling return outside of the function contest: PHP Manual - Return.
Edit:
Don't know if this is useful, but i think that including a file to get a piece of HTML, is not a good option. It's not scalable. You could try with something like MVC. You could ask your controller to renderize the content of what you want.
$view = $controler->getElement('box');
$page = "<div class='media-title'><h2>{$title}</h2></div><div class='media-image'>{$image}</div><div class="inlinebox">" . $view . "</div><div class='media-desc'>{$desc}</div>";
Try to decouple your code.
I recommend you to take a look to some MVC Framework, in my opinion, the best one is CakePHP.

Categories