I usually run code like this just fine:
$ZANE_REGISTER_RULES='this wont print';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='this will actually print';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
But sometime (eg: if I put this inside a phpBB page) this doesn't work (the echo says "this wont print") unless I declare the variable global the first time too:
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='my rulessssssssssssssss';
myTest();
function myTest()
{
**global $ZANE_REGISTER_RULES**;
$ZANE_REGISTER_RULES='funziona';
}
echo $ZANE_REGISTER_RULES; //will print "this will actually print"
I'm pretty sure that the first way is the correct one and the second one just doesn't mean anything, nevertheless the second one works, the first one doesn't.
PLEASE don't waste time replying "global are bad programming" because this is not the issue at hand, neither "why would you do such a thing?" because this is obviusly an example.
There is only one reason why this might be happening: the code in the second example is being compiled in the context of a function. That's why $ZANE_REGISTER_RULES has local scope by default.
If there is no enclosing function in the source file where the code itself appears, this means that the file is being included by some other file inside a function context, for example:
var_access.php
echo "Hello ".$name."\n";
echo "Hello ".$_GLOBALS['name']."\n";
test_1.php
// Here var_access.php is included in the global context
$name = 'world';
include('var_access.php'); // Prints "Hello world" twice
test_2.php
// Here var_access.php is included in a function context
$name = 'world';
function func() {
$name = 'function world';
include('var_access.php'); // Prints "Hello world" and "Hello function world"
}
Related
Hey i have problem code:
$$videoList[$i]["id"] call variable -> $hello
but i need add one more letter to the end
$$videoList[$i]["id"]+W call varriable -> $helloW
<p>'.$$videoList[$i]["id"].'</p>
I don't advise to do what you are doing.
The code becomes a true hell that nobody can mantain in the long run.
Anyway, if you hate the world, you can achieve with ${$videoList[$i]["id"].'W'}
As for a better understanding, see this example:
<?php
$hello = 'sayHello';
$helloW = 'with W';
$myVar = 'hello';
echo $myVar; //hello
echo $$myVar; //sayHello
echo $$myVar.'W'; //sayHelloW
echo ${$myVar.'W'}; //with W
I want to mix a variable after call a function, but not when I set the variable.
My example code:
<?php
$greeting = "hi! {$gbye}";
function greetings() {
global $greeting;
$gbye = "goodbye!";
return $greeting;
}
echo greetings();
?>
Fiddle: http://phpfiddle.org/main/code/kd5w-p7q4
I tried escaping the $ symbol: \$, but this only gives me the complete text. And replacing the escaped symbol make the same.
The $gbye variable is inside a language file, by this reason, I have to save the word ($gbye) until I call the function (to replace it as if the full string ($greeting = "hi! {$gbye}";) was inside the function). It's just an example.
So what can I do?
For language file usage, you may want to use your own meta keyword, instead of php variable syntax. This is ensure what you want to do is seperated from what PHP wants to do. This will save you from future bugs and maintenance effort. For example,
<?php
$greeting = "hi! #gbye#";
function greetings() {
global $greeting;
return str_replace("#gbye#", "goodbye!", $greeting);
}
echo greetings();
?>
I am wondering if there is any real benefit to using this...
function getSomeContent() {
ob_start(function($content) {
// ... modify content ...
return $content;
}
// ... output stuff ...
return ob_get_clean();
}
...as opposed to this...
function getSomeContent() {
ob_start();
// ... output stuff ...
$result = ob_get_clean();
// ... modify content ...
return $result;
}
...?
Assume the "output stuff" and "modify content" parts are the same in each case. The key point is that the "modify content" has changed its location, being in a callback in the first case, and being "inline" in the second case.
Is there a performance benefit of one over the other? For example, does the second form make two copies of the buffer contents when the first uses only one? Or is it purely a coding style decision? Why would you choose one form over the other?
I can see there are differences in scope access, because any variables in the enclosing scope will be available in the "modify content" part of the second example, where they would have to be "passed in" with a use clause in the first example. In fact this is exactly why I would normally choose the second form.
Now your code is clear yes, in your first samples you given a case where you used $result twice (that wasn't a good idea).
My main idea is : you call ob_start with a callback only if you do not need to use your $result in your current scope. Your first example becomes :
ob_start(function($content) {
// ... modify content ...
return $content;
}
// ... output stuff ...
ob_end_clean();
In this case, the job with $result is made in a new scope and this can make your code cleaner (example: you call ob_start(array($this, 'method'));), and you don't need to unset your $result to free it from your main scope at the end of your job (I assume you're doing something else of course).
Just to clarify Ninsuo's correct answer a bit.
My two code samples actually do not produce the same result. In fact, using the callback in combination with ob_get_clean() is completely useless.
This is because the callback is applied when cleaning or flushing the buffer.
However ob_get_clean() retrieves the contents first, and then cleans the buffer. Which means that the contents returned are not the result returned by the callback, but the input passed to the callback.
I wrote these two simple (and hacky) scripts to demonstrate.
This one uses ob_get_clean() and does not produce the correct result:
// Tests the use of callbacks with ob_get_clean().
class TestWithGetClean {
// This variable is set when obcallback is called.
public $foo = null;
// The output buffer callback.
public function obcallback($value) {
$this->foo = 'set';
return $value . '(modified)';
}
// Main method.
public function run() {
ob_start(array($this, 'obcallback'));
echo 'this is the output', PHP_EOL;
return ob_get_clean();
}
}
// Run the test with ob_get_clean().
$t = new TestWithGetClean();
echo $t->run(); // This method returns a value in this test. (But not the correct value!)
echo $t->foo, PHP_EOL;
The output from running this is:
this is the output
set
The text '(modified)' does not appear anywhere. Note however that the instance variable $foo is set, so the callback is definitely called, however the output is not as I originally expected.
Compare to this one which uses ob_end_flush():
// Tests the use of callbacks with ob_end_flush().
class TestWithEndFlush {
// This variable is set when obcallback is called.
public $foo = null;
// The output buffer callback.
public function obcallback($value) {
$this->foo = 'set';
return $value . '(modified)' . PHP_EOL;
}
// Main method.
public function run() {
ob_start(array($this, 'obcallback'));
echo 'this is the output', PHP_EOL;
ob_end_flush();
}
}
// Run the test with ob_end_flush().
$t2 = new TestWithEndFlush();
$t2->run(); // This method produces output in this test.
echo $t2->foo, PHP_EOL;
This one produces the following output:
this is the output
(modified)
set
However, this is of course not as useful because the output goes directly to the client, so we cannot further manipulate the result. (For example, wrapping the text in a Symfony HttpFoundation Component Request object).
im working with a large team, and im making functions that return html code, and im echoing the result of those functions to get the final page. The thing is, i need some scrap of code developed by other member of the team, and i need it to be a string, but the code is available as a php file which im supposed to include or require inside my page.
Since im not writing an ht;ml page, but a function that generate that code, i need to turn the resulting html of the require statement into a string to concatenate it to the code generated by my function.
Is there any way to evaluate the require and concatenate its result to my strings?
Ive tried the function eval(), but didnt work, and read some thing about get_the_content(), but it isnt working either. I dont know if i need to import something, i think it have something to do with wordpress, and im using raw php.
thanks for all your help!!! =)
Try the ob_...() family of functions. For example:
<?php
function f(){
echo 'foo';
}
//start buffering output. now output will be sent to an internal buffer instead of to the browser.
ob_start();
//call a function that echos some stuff
f();
//save the current buffer contents to a variable
$foo = ob_get_clean();
echo 'bar';
echo $foo;
//result: barfoo
?>
If you want to put the echo'd result of an include into a variable, you could do something like this:
//untested
function get_include($file){
ob_start();
include($file);
return ob_get_clean();
}
or if you want to put the echo'd result of a function call into a variable, you could do something like this:
//untested
//signature: get_from_function(callback $function, [mixed $param1, [mixed $param2, ... ]])
function get_from_function($function){
$args = func_get_args();
shift($args);
ob_start();
call_user_func_array($function,$args);
return ob_get_clean();
}
Depending on how the other file works...
If the other file can be changed to return a value, then you should use:
$content = require 'otherfile';
If the other file simply uses echo or some other way to print directly, use:
ob_start();
require 'otherfile';
$content = ob_get_clean();
You can receive string with include or require but you have to update those files before including to add return statement.
the file to be included should return result like this
<?php
$var = 'PHP';
return $var;
?>
and you can receive the $var data by including that file
$foo = include 'file.php';
echo $foo; // will print PHP
Documentation section
I'm new to PHP and web scripting in general so this a newb question.
Currently i'm a creating an instance to an object, yet when I call the constructor
the script slienty shuts down... it doesn't call the next function and I don't know why.
Any help would be welcome.
Here is the code.
<?php
class product {
var $ssProductName;
var $ssVendorName;
var $ssDescr;
var $ssURI;
// Clean constructor, strings must be cleaned before use
function __construct($ssProd, $ssVendor, $ssD, $ssU) {
$this->$ssProductName = $ssProd;
$this->$ssVendorName = $ssVendor;
$this->$ssDescr = $ssD;
$this->$ssURI = $ssU;
}
// print a table of the values
function DisplayOneEntry() {
echo '<table border="1">
<tr>
<td>'.$this->$ssProductName.'</td>
<td>'.$this->$ssVendorName.'</td>
<td>'.$this->$ssDescr.'</td>
<td>'.$this->$ssURI.'</td>
</tr>
</table>';
}
}
echo "<HTML>";
echo "A";
$newP = new product("Redhat", "Redhat corp", "Leader in", "www.redhat.com");
echo "B";
$newP->DisplayOneEntry();
echo "</HTML>";
?>
But the output is just:
<HTML>
A
Then nothing else.
This is running on a hosting provider using php 5.2.9 and Apache 2.2.
You need to access the member variables with:
$this->variableName
Not:
$this->$variableName
$this->$ssProductName = $ssProd;
should be
$this->ssProductName = $ssProd;
no $ after the ->
The syntax $this->$foo is a variable variable referencing the class attribute with the name of the value of $foo. So if $foo has the value bar, $this->$foo would reference $foo->bar and not $this->foo.
So just remove the $ after $this-> and it should work.
That is because your php script is erroneous. To catch such errors, you should run it on a debugging server (with display_errors set to On) or use other logging methods.
However, the main problem is you are accessing object members the wrong way; there's no second dollar sign. Instead of
$this->$ssProductName = $ssProd;
use
$this->ssProductName = $ssProd;