echo variable before call function - php

First of all I should say this code is a sample and i remake for you to show what i want my original code too huge and can't post here, but the logic and functions similar to this example.
I made a dynamic title in a function called getTitle() and it show on #side-bar now i want to use this title in h1 tag too, but as you see h1 tag rendered before this function, and i'm not able to move h1 tag after #side-bar. Now i want to know how can i echo a variable that generated from a function, before call this function.
PHP:
<?php
function getTitle(){
global $title;
// some code to generate dynamic title
$title = "example title";
echo $sample = "123";
return $title;
// other code
}
?>
HTML:
echo <h1><?=$title;?></h1>;
<div id="side-bar"><?php getTitle(); ?></div> <!-- call -->
I know if i move $title after calling the function getTitle(); it works fine but i need to echo $title before calling this function. Is it possible? or any idea, or logic to do this?
Also i know i can clone the title from side-bar to h1 with javascript or etc.. but this is a h1 tag and can't fill it after page load in client side.

PHP:
<?php
function getTitle(){
// some code to generate dynamic title
return ['title' => 'Example title', 'sample' => '123'];
}
?>
HTML:
$response=getTitle();
echo <h1><?=$response["sample"];?></h1>;
<div id="side-bar"><?php $response["title"]; ?></div> <!-- call -->

Your approach is wrong. Instructions are not executed after return statement.
PHP function
<?php
function getTitle(){
$title = /*generate dynamic title*/;
return $title;
}
?>
HTML
<?php $generatedTitle = getTitle(); ?>
<h1><?php echo $generatedTitle; ?></h1>
<div id="side-bar"><?php echo $generatedTitle; ?></div>

Related

function as function input php

I want to create my own template for building my next web projects.
But my problem is that I am trying to create my own template system with my own function, also to learn more about coding on my on aswell.
I'm trying to improve my code to be me clean/smooth as I code.
But now I ran into this problem
a-function-file.php
<?php
$Website_info = array("SiteTitle"=>"CLiCK", "BaseUrl"=>"http://localhost/CLick/");
//css styles her
$website_styles = array(
array("src"=>"libs/css/bootstrap.min.css", "type"=>"text/css"),
array("src"=>"libs/themes/click.css", "type"=>"text/css")
);
//javascripts her
$website_scripts = array(
array("src"=>"libs/js/bootstrap.min.js", "type"=>"text/javascript")
);
$website_navigation_top_links = array(
array("link"=>"index.php","name"=>"Home")
);
function Click_styles()
{
global $website_styles;
$styleOutput = "";
foreach ($website_styles as $key => $CssStyle):
$styleOutput .= "<link href='".$CssStyle["src"]."' rel='stylesheet' type='".$CssStyle["type"]."'>\n";
endforeach;
return $styleOutput;
}
//my function to create html codes within head tags
function Click_header()
{
//Getting website info into function
global $Website_info;
global $website_styles;
$ImpotedStyles = Click_styles();
//creating the html (can maybe be created more clean later)
$Header_output = "<title>".$Website_info["SiteTitle"]."</title>\n";
$Header_output .= "<base href='".$Website_info["BaseUrl"]."' />\n";
$Header_output = $Header_output.$ImpotedStyles;
// return the complied output (as HTML)
return $Header_output;
}
?>
So far so good, because this works if I write
<?php echo Click_header();?>
But I want to use the function like this with, by passing it a function as an argument
<?php
//the function that doesnt work
function printHTML($ThisShouldBeAFunctionNotAVar, $Description="none") {
echo $ThisShouldBeAFunctionNotAVar
}
?>
<?php
//how I want to use the function
printHTML(Click_header(), "The website header");
//and maybe if I had a footer I could display the return of that function too
printHTML(Click_foter(), "a smart footer function");
?>
I hope you can help me with this or get a better understanding for maybe something smarter
I fount this solution on my own
<?php
function printHTML($CustomFunction,$Description="")
{
$function = ($CustomFunction;
echo $function();
}
?>

content displaying out side of html tags for return and echo

I know that echo will echo the content and return will return the contents for further processing. How ever, I have said function:
class Content{
protected $_html = '';
public function display_content(){
$this->_html = 'content';
}
public function __toString(){
return $this->html;
}
}
then some where I have the following:
$content = new Content();
<p><?php $content->disaply_content(); ?></p>
I get:
<p></p>
content
as the source code for the page. doesn't matter if I echo or just return, either way it displays out side the tag.
Ideas?
I'm not sure where the second 'content' is coming from but note that:
<?php $content->display_content();?>
Will not display anything between the <p> tags. You should use:
<?php echo $content->display_content();?>
(I assume the disaply_content() was a typo in the question and not in the code).

Create element using call_user_func in PHP

I have a PHP stuff that uses call_user_func to create element/objects to a certain function where it was place.
Example functions.php File:
function head($args=null){
echo $args;
}
function footer($args=null){
echo $args;
}
function createHeadTexts(){
echo 'This is header area';
}
function createFooterTexts(){
echo 'This is footer area';
}
//function to call this elements
function addParam($arg, $val){
call_user_func($arg, call_user_func($val));
}
Example index.php file:
head()
This is contents area...
footer()
Back to my functions.php file, I have added a call to function which is
addParam('head','createHeadTexts')//which is I thought has to be added on a header area.
addParam('footer','createHeadTexts')//which is I thought has to be added on a footer area too.
But I came to an issue when I tried to view my PHP page.
it looks like this :
This is header area This is footer area
This is contents area...
I thought the texts should be display like this:
This is header area
This is contents area...
This is footer area
The only functions should be place to my index.php file is head() and footer().
The head() should be appear before the web contents, and footer() should be appear after the contents.
If I would like to create an element/objects/scripts to head() it should be addParam('head','function to create element/object/scripts');
Please help me how to fix this or is there any other way to use aside call_user_func?
Thanks,
I just tested this and it came out allright:
<?php
function head($args=null){
echo $args;
}
function footer($args=null){
echo $args;
}
function createHeadTexts(){
echo 'This is header area';
}
function createFooterTexts(){
echo 'This is footer area';
}
// function to call this elements
function addParam($arg, $val){
call_user_func($arg, call_user_func($val));
}
addParam('head','createHeadTexts');
echo '<br />This is contents area...<br />';
addParam('footer','createFooterTexts');
?>
And the output:
This is header area
This is contents area...
This is footer area
Maybe you forgot to change some arguments? The only thing I changed was
addParam('footer','createHeadTexts') to addParam('footer','create FOOTER Texts')

Dynamic Titles in my codeigniter header.php

I have a header.php I'm loading in my controllers for every page. However I want to have dynamic titles for each page. My idea was to pass a $title variable into the view as I'm loading it:
//Home Controller
function index()
{
$data['title'] = "Dynamic Title";
$this->load->view('header', $data);
$this->load->view('layouts/home');
$this->load->view('footer');
}
and then check for the $title variable in my header.php
<title>
<?php if ($title)
{
echo $title;
}
else
{
echo 'Default Title';
}
endif; ?>
</title>
However this doesn't work and I get a blank page. I think it is my syntax for the header.php but I can't figure out why.
Proper if Syntax
Your syntax on the if-statement is a bit off. You can use either:
if (condition) {
// do a
} else {
// do b
}
Or
if (condition) :
// do a
else :
// do b
endif;
You seem to have transposed the ending of the latter onto the former.
Using the Ternary Operator in Title
Once you've made that change, your title can be printed as easily as:
<title><?php echo isset($title) ? $title : 'Default Title' ; ?></title>
Alternative View Loading
Another method of loading views is to work with a single template file:
$data['title'] = 'Foo Bar';
$data['content'] = 'indexPage';
$this->load->view('template', $data);
This loads the template.php file as your view. Within this file you load your subsequent parts:
<?php $this->load->view("_header"); ?>
<?php $this->load->view($content); ?>
<?php $this->load->view("_footer"); ?>
By no means is this necessary, but it may help you maintain brevity in your controller.
Well I would try doing a var dump of $title in the view, just to see if it's getting passed at all.
Also, you don't need "endif;" since you're ending the if statement with the last curly brace.

What is the best way to include a php file as a template?

I have simple template that's html mostly and then pulls some stuff out of SQL via PHP and I want to include this template in three different spots of another php file. What is the best way to do this? Can I include it and then print the contents?
Example of template:
Price: <?php echo $price ?>
and, for example, I have another php file that will show the template file only if the date is more than two days after a date in SQL.
The best way is to pass everything in an associative array.
class Template {
public function render($_page, $_data) {
extract($_data);
include($_page);
}
}
To build the template:
$data = array('title' => 'My Page', 'text' => 'My Paragraph');
$Template = new Template();
$Template->render('/path/to/file.php', $data);
Your template page could be something like this:
<h1><?php echo $title; ?></h1>
<p><?php echo $text; ?></p>
Extract is a really nifty function that can unpack an associative array into the local namespace so that you can just do stuff like echo $title;.
Edit: Added underscores to prevent name conflicts just in case you extract something containing a variable '$page' or '$data'.
Put your data in an array/object and pass it to the following function as a second argument:
function template_contents($file, $model) {
if (!is_file($file)) {
throw new Exception("Template not found");
}
ob_start();
include $file;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
Then:
Price: <?php echo template_contents("/path/to/file.php", $model); ?>

Categories