Why aren't my variable seen when called with require ?
function.php
<?php
function paginator(){
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
$GLOBALS['$page'] = $key;
}
}
$page = $GLOBALS['$page'];
$next = $page+1;
$previous = $page-1;
}
?>
content.php
<?php
session_start();
require './functions.php';
paginator();
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Pagination</title>
</head>
<body>
<h2>Now on Page : <?php echo $page?></h2>
<a href="<?php echo $links[$next] ?>" >Next</a>
<br><br><br>
<a href="<?php echo $links[$previous]?>" >Previous</a>
<br>
</body>
</html>
I would like to be able to see my variables, when using the require function as this piece of code will be on every page. This might be a very noobish concept to grasp but I would really like someone to illustrate the concept properly.
This seemed to work, Thank you everyone.
<?php
$links = array("index.php", "services.php", "content.php","contact_us.php" );
$trimslug = substr(strrchr($_SERVER['PHP_SELF'], "/"), 1);
$page = null;
function paginator(){
global $links,$trimslug,$next,$previous,$page;
foreach ($links as $key => $value) {
if ($value == $trimslug ) {
// $GLOBALS['$page'] = $key;
$page = $key;
}
}
$next = $page+1;
$previous = $page-1;
}
?>
The variables inside paginator are only in the scope of the function, not the php file. If you want to access them outside that function, just move those variables outside of it. Eg
$page=null;
$links=...
function paginator(){
...
}
This is because the variables are defined in the scope of the function paginator();
If you want them to be accesible in the scope of content.php, either declare them like this:
global $variable = 'value';
Or, just declare them in function.php without the need of the function & it's subsequent call in content.php.
Variables in PHP are limited to the scope of the function, unless called via an argument or by adding to the global array.
Global arrays are bad practice, just sayin.
You could always make the variables into a private class and call it as needed, though that's pretty tricky for beginners.
Related
I have a variable named $url in the top of my file:
<?php
$url = "http://myurl.com";
Later in the same file, I have this code:
<?php
$url = "http://myurl.com";
[...]
function errorOut($error, $type = "info", $rel = "/")
{
echo $url;
}
?>
However, that doesn't work, because it says $url isn't a valid variable. I have to do this:
<?php
$url = "http://myurl.com";
[...]
function errorOut($error, $type = "info", $rel = "/")
{
$url = "http://myurl.com";
echo $url;
}
?>
This doesn't make any sense to me because it shouldn't be out of scope because it's a layer above the function. How do I make it use the earlier $url variable?
They are not in the same scope. You have to let PHP know you will be using that global locally. It is preferable to not use a global and instead pass it as a variable though.
<?php
$url = "http://myurl.com";
[...]
function errorOut($error, $type = "info", $rel = "/")
{
global $url;
echo $url;
}
?>
See Variable scope for more information.
I was talking to someone in an IRC about this (he posted on here too before I joined), he said I should use
define("URL", 'http://example.com');
And whenever I reference that variable I should use URL, not $url
by passing the $url in your function:
function errorOut($error, $type = "info", $rel = "/", $url) //<<< here
and also calling it:
errorOut('...','...','...',$url);
NON WORKING EXAMPLE AS SEEN IN YOUR ANSWER
$a = 'test1';
$b = 'test2';
define ('URL','one');
define ('URL', 'two');
test($a,$b);
function test ($a,$b){
echo $a;
echo $b;
echo URL;
}
Won't work, URL will stay at 'one' // Will only work if you never want to change URL
I'm trying to print my key/value pairs of data in my CodeIgniter view. However, I'm getting the following error. What I'm I doing wrong?
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/search_page2.php
Line Number: 8
application/controller/search.php
// ...
$this->load->library('/twitter/TwitterAPIExchange', $settings);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=johndoe';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
// ...
application/views/search_page2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Twitter Test</title>
</head>
<body>
<?php print_r($data); ?>
<?php foreach ($data as $key => $value): ?>
<h2><?php echo $key . ' ' . $value . '<br />'; ?></h2>
<?php endforeach ?>
</body>
</html>
to get the data array accessible in the view do like
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$data['data'] = $data;
$this->load->view('search_page2', $data);
else only the variables with names as its keys will be available in the view not the data variable we pass.
update:
this is in response to your comment to juan's answer
Actually if you are trying make it working in the other way proposed.
controller code will be having no change from the code you posted.
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
but in the view code you will need to just do.
<h2>url <?PHP echo $url; ?><br /></h2>
<h2>getfield <?PHP echo $getfield; ?><br /></h2>
<h2>requestMethod <?PHP echo $requestMethod; ?><br /></h2>
instead of the foreach loop as your keys in $data are already available as respective named variables inside the view.
The variables to use in your template are
$url, $getfield, $requestMethod
$data is the container for the variables that are passed to the view and not accessible directly
If you do need $data accessible to the view, use a different wrapper object
$container = array();
$container ['url'] = $url;
$container ['getfield'] = $getfield;
$container ['requestMethod'] = $requestMethod;
$container ['data'] = $data;
$this->load->view('search_page2', $container);
I'm stuck on how to write the test.php page result (after php has run) to a string:
testFunctions.php:
<?php
function htmlify($html, $format){
if ($format == "print"){
$html = str_replace("<", "<", $html);
$html = str_replace(">", ">", $html);
$html = str_replace(" ", " ", $html);
$html = nl2br($html);
return $html;
}
};
$input = <<<HTML
<div style="background color:#959595; width:400px;">
<br>
input <b>text</b>
<br>
</div>
HTML;
function content($input, $mode){
if ($mode =="display"){
return $input;
}
else if ($mode =="source"){
return htmlify($input, "print");
};
};
function pagePrint($page){
$a = array(
'file_get_contents' => array($page),
'htmlify' => array($page, "print")
);
foreach($a as $func=>$args){
$x = call_user_func_array($func, $args);
$page .= $x;
}
return $page;
};
$file = "test.php";
?>
test.php:
<?php include "testFunctions.php"; ?>
<br><hr>here is the rendered html:<hr>
<?php $a = content($input, "display"); echo $a; ?>
<br><hr>here is the source code:<hr>
<?php $a = content($input, "source"); echo $a; ?>
<br><hr>here is the source code of the entire page after the php has been executed:<hr>
<div style="margin-left:40px; background-color:#ebebeb;">
<?php $a = pagePrint($file); echo $a; ?>
</div>
I'd like to keep all the php in the testFunctions.php file, so I can place simple function calls into templates for html emails.
Thanks!
You can use output buffering to capture the output of an included file and assign it to variable:
function pagePrint($page, array $args){
extract($args, EXTR_SKIP);
ob_start();
include $page;
$html = ob_get_clean();
return $html;
}
pagePrint("test.php", array("myvar" => "some value");
And with test.php
<h1><?php echo $myvar; ?></h1>
Would output:
<h1>some value</h1>
This may not be exactly what you're looking for but it seems you want to build an engine of sorts for processing email templates into which you can put php functions? You might check out http://phpsavant.com/ which is a simple template engine that will let you put in php functions directly into a template file as well as basic variable assignment.
I'm not sure what printPage is supposed to be doing but I would re-write it like this just to make it more obvious because the array of function calls is a bit complicated and I think this is all that is really happening:
function pagePrint($page) {
$contents = file_get_contents($page);
return $page . htmlify($contents,'print');
};
and you might consider getting rid of htmlify() function and use either of the built-in functions htmlentities() or htmlspecialchars()
Seems like my original method may not have been the best way of going about it. Instead of posing a new question on the same topic, figured it was better to offer an alternate method and see if it leads to the solution I am after.
testFunctions.php:
$content1 = "WHOA!";
$content2 = "HEY!";
$file = "test.html";
$o = file_get_contents('test.html');
$o = ".$o.";
echo $o;
?>
text.php:
<hr>this should say "WHOA!":<hr>
$content1
<br><hr>this should say "HEY!":<hr>
$content2
I'm basically trying to get $o to return a string of the test.php file, but I want the php variables to be parsed. as if it was read like this:
$o = "
<html>$content1</html>
";
or
$o = <<<HTML
<html>$content1</html>
HTML;
Thanks!
Basically, I need to view the PHP code of a file, after includes. I am trying to see EXACTLY what PHP code is run. eg...
<?php // a.php
$a = 10;
?>
<?php // b.php
include('a.php');
$b = 20;
?>
If I was trying to get the code of b.php, it would display the following:
<?php
$a = 10;
$b = 20;
?>
Is that possible? If so, how?
// at the end of your script
<?php
$totalRunCode = '';
$scripts = get_included_files();
foreach($scripts as $script)
{
$totalRunCode .= file_get_contents($script);
}
// do whatever with totalRunCode
Though I don't know why you'd want to do this.
I have a function that I'd like plug a view file. It's pretty simple when you just need to echo one or two things but I have some complicated html and so would like to take advantage of alternate php syntax for the following foreach loop and if statements:
UPDATE I corrected the CI->load->view to include the 3rd parameter according to tpaksu's suggestion. It's closer to working but still not quite right. See comments below in the code:
<?
function displayComments(array $comments, $parentId = null) {
$CI=& get_instance();
foreach($comments as $comment){
if($comment['replied_to_id'] == $parentId){
echo $CI->load->view('reviews/comment_list', $comments, true); // this doesn't work, it only shows the last array member
// echo $comment['comment']; this works as expected
}
}
}
displayComments($comments, $parentId = null);
?>
Here's what the 'reviews/comment list view file looks like in its simplest form:
<ul>
<? foreach($comments as $comment): $comment=$comment['comment']?>
<li>
<?echo $comment?>
</li>
<?endforeach;>
</ul>
Would anyone know to how embed view files into a function?
I usually use to have a snippet_helper in my projects. There, I have many many functions wich generates chunks of reusable things (also called modules or components).
I do like, also, the WordPress approach wich use to return data in the main function (you may need more treatments before display) and a "sister function" to directly echo the results.
I think it'll works with you. For example:
function get_display_comments(array $comments, $parentId = NULL)
{
$CI =& get_instance();
$return = '';
foreach ($comments AS $comment)
{
if ($comment['replied_to_id'] == $parentId)
{
$return .= $CI->load->view('reviews/comment_list', $comments, TRUE);
}
}
return $return;
}
function display_comments(array $comments, $parentId = NULL)
{
echo get_display_comments($comments, $parentId);
}
Your content on the first file :
<?php
$CI=& get_instance();
echo $CI->load->view('reviews/comment_list', $comments, true);
?>
And the reviews/comment_list view :
<ul>
<?php
foreach($comments as $comment){
$comment=$comment['comment'];
echo "<li>" . $comment . "</li>";
}
?>
</ul>
just write this and try again.