Overriding var_dump globally? - php

I don't like the way var_dump prints out objects. I want to override it with this function:
function var_dump($object, $die = true) {
print '<pre>';
print_r($object);
if ($die) die();
}
I know how to override it in my application, but is there a way to override it globally for all sites on a PHP config level?

You can not do that currently (via "good way") in PHP. And more - you shouldn't.
var_dump() is doing right for what it's intended: plain output and nothing more. If you want to change that, then by definition you want some user-defined behavior. Therefore:
Create your own function. That is what you have now. User-defined functions are for user-defined behavior.
Or else, if you want to do it with var_dump() name by some reason, use namespace like:
namespace Utils;
function var_dump($var, $exit=true, $return=true)
{
$result = sprintf('<pre>%s</pre>', print_r($var, true));
if($exit)
{
echo $result;
exit;
}
if($return)
{
return $result;
}
echo $result;
}
so usage will look like:
$obj = new StdClass();
$str = \Utils\var_dump($obj, false);
//do domething with $str
echo $str; //or use second false
Worst case: runkit_function_redefine() Remember, this is evil. You should not do that because redefining goes against what is function and why it was defined. It is a global side-effect and you should avoid such behavior.

You can use the override_function: http://www.php.net/manual/en/function.override-function.php to replace the behavior of the var_dump function. If you want to include this piece of code in all of your sites, you can put this in your php.ini file:
php_value auto_prepend_file /path/to/file_where_you_override_function.php

Related

Using a function to initialise a variable if it not set - PHP

Upon executing a script, sometimes the variable will be set, and sometimes it won't. The times that it isn't, I'm given a notice that the variable is not defined.
In efforts to clear the notice, I simple added the following code
if(!isset($var)) {
$var = NULL;
}
That works just as needed because it tests if the variable isn't already set so that we don't set something that we need to NULL. But in a file where there are over 60 variables that are of this case and more to come, I thought creating a simple function to do so would be easier. So I started with this:
function init($var) {
if(!isset($var)) {
return $var = NULL;
}
}
Obviously that doesn't work and is also riddled with errors that will annoy most programmers out there (such as the !isset() inside a function, not supplying a return statement in case the if statement is false, etc.) but that's just to give you the basic jist of what I need so in the code I can just call init($var); to test if the variable isn't already set, and then creates one and sets it to NULL to avoid the notice.
Is this even possible? To use a function to test if a variable is already set outside of the function? Thanks in advance :)
You can't use a function to check if a variable exists without it being initialized in the process of passing it to the function as an argument. You can, however, define an array of variable names your script requires then loop through them and check if they exist one by one. Such as:
foreach(array('username','userid','userrole','posts','dob','friends') as $var)
{
if(!isset($$var))$$var=NULL;
}
Edit: Simplifying user4035's approach, you could get the function down to:
<?php
function init(&$var){}
init($myVariable);
var_dump($myVariable);
Or even avoid a function altogether:
<?php
array(&$var1,&$var2,&$var3);//define several variables in one shot as NULL if not already defined.
var_dump($var1);
var_dump($var2);
var_dump($var3);
Another approach would be to use extract:
<?php
$defaults=array('username'=>NULL,'userid'=>0,'userrole'=>'guest','posts'=>0,'dob'=>0,'friends'=>array());
$userid=24334;
$username='bob';
$friends=array(2,5,7);
extract($defaults, EXTR_SKIP);
echo '<pre>';
print_r(
array(
'userid'=>$userid,
'username'=>$username,
'friends'=>$friends,
'userrole'=>$userrole,
'posts'=>$posts,
'dob'=>$dob)
);
echo '</pre>';
Another approach would be to temporarily disable error reporting:
<?php
$v=ini_get("error_reporting");
error_reporting(0);
echo 'One';
echo $doh;//Use an undefined variable
echo ' Two';
error_reporting($v);
I'd advise against this approach though because it is just hiding the errors rather than fixing them and will also hide errors worthy of your attention.
And my personal favorite would be to take advantage of namespaces.
Usually you'd put these into separate files but I put them into a single snippet for your convenience:
<?php
namespace //This is the global namespace
{
$config=array('production'=>0);
}
namespace MyScript
{
//Initialize all variables for our script
//anything not defined here will be inherited from the global namespace
$username=NULL;
$userid=NULL;
$userrole=NULL;
$posts=NULL;
$dob=NULL;
$friends=NULL;
}
namespace MyScript\Main
{
//Define only two variables for our script
//Everything else will be inherited from the parent namespace if not defined
$username='Ultimater';
$userid=4;
echo '<pre>';
print_r(
array(
'userid'=>$userid,
'username'=>$username,
'friends'=>$friends,
'userrole'=>$userrole,
'posts'=>$posts,
'dob'=>$dob,
'config'=>$config)
);
echo '</pre>';
}
If your intention is this:
if(variable is not set)
set variable to NULL
then it's quite easy to implement, using a reference:
function init(&$var) {
if(!isset($var)) {
$var = NULL;
}
}
Testing:
<?php
error_reporting(E_ALL);
function init(&$var) {
if(!isset($var)) {
$var = NULL;
}
}
init($x);
var_dump($x);
Output:
NULL

Is there a way to set Global Variables to be available by default within PHP functions?

Is there any way to do this / specify this in the php.ini configuration file? It would be really nice, at least for local server purposes, just to write functions without having to write the global keyword every time a global variable is used within the method.
Any way to do this?
EDIT:
What I mean is being to simply write this:
Example file "index.php":
$MY_ARRAY = array();
include("functions.php");
And then in "functions.php":
function addToArray($pMessage) {
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Instead of:
And then in "functions.php":
function addToArray($pMessage) {
global $MY_ARRAY;
$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
Yeah! You can setup a prepend file in PHP.
See: http://www.php.net/manual/en/ini.core.php#ini.auto-prepend-file
I still do not understand the purpose. But if I need to just remove the GLOBAL keyword from mentioning everytime, I would prefer to use a class with static array.
Something like this:
<?php
// Config.php
class Config {
public static $MY_ARRAY = array();
}
?>
And then include this file from your loader just call like this:
function addToArray($pMessage) {
Config::$MY_ARRAY[] = "<a href='somelink.php'>$pMessage</a>";
}
That will work.

How do I verify that this function is a string in PHPUnit?

Here's the code for my original PHP code:
public function outputText() {
$i = 1;
foreach($this->sorted_data as $this->data) {
echo "$i. ".$this->data[0]."<br/>";
$i++;
}
}
And here's the code for the PHPUnit:
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
$output = $yn->outputText();
$this->assertTrue(is_string($output));
//if(!is_string($yn->get()))
// return false;
//$this->assertNotEmpty($yn->get());
}
The class is called SortThisData in the original PHP file.
When I used gettype(), it said it was null. I'm trying to verify that it is a string so it can pass in PHPUnit. Is there a way I can do this?
You're looking for assertInternalType().
Update: I didn't realize you were echoing the output. You will probably need to use output buffering to capture the text.
public function testVerify() {
$yn = new SortThisData();
$yn->readFile("input.txt");
// start output buffering and capture the output
ob_start();
$yn->outputText();
$output = ob_get_clean();
$this->assertInternalType('string', $output);
}
No disagreement with Baylor's answer. To answer the question, as asked, what you had was also good enough:
$this->assertTrue(is_string($output));
Or you could have done:
$this->assertEquals('string',gettype($output));
(The advantage of the latter is, when it fails, it will also tell you the type of $output; assertTrue will only tell you that something failed.)
assertInternalType() does exactly that, but was only introduced in PHPUnit 3.5, and you will still find PHPUnit 3.4 in use on some machines.

PHP include/require within a function

Is it possible to have return statements inside an included file that is inside a function in PHP?
I am looking to do this as I have lots of functions in separate files and they all have a large chunk of shared code at the top.
As in
function sync() {
include_once file.php;
echo "Test";
}
file.php:
...
return "Something";
At the moment the return something appears to break out of the include_once and not the sync function, is it possible for the included file's return to break out?
Sorry for the slightly odly worked question, hope I made it make sense.
Thanks,
You can return data from included file into calling file via return statement.
include.php
return array("code" => "007", "name => "James Bond");
file.php
$result = include_once "include.php";
var_dump("result);
But you cannot call return $something; and have it as return statement within calling script. return works only within current scope.
EDIT:
I am looking to do this as I have lots
of functions in separate files and
they all have a large chunk of shared
code at the top.
In this case why don't you put this "shared code" into separate functions instead -- that will do the job nicely as one of the purposes of having functions is to reuse your code in different places without writing it again.
return will not work, but you can use the output buffer if you are trying to echo some stuff in your include file and return it somewhere else;
function sync() {
ob_start();
include "file.php";
$output = ob_get_clean();
// now what ever you echoed in the file.php is inside the output variable
return $output;
}
I don't think it works like that. The include does not simply put the code in place, it also evaluates it. So the return means that your 'include' function call will return the value.
see also the part in the manual about this:
Handling Returns: It is possible to
execute a return() statement inside an
included file in order to terminate
processing in that file and return to
the script which called it.
The return statement returns the included file, and does not insert a "return" statement.
The manual has an example (example #5) that shows what 'return' does:
Simplified example:
return.php
<?php
$var = 'PHP';
return $var;
?>
testreturns.php
<?php
$foo = include 'return.php';
echo $foo; // prints 'PHP'
?>
I think you're expecting return to behave more like an exception than a return statement. Take the following code for example:
return.php:
return true;
?>
exception.php:
<?php
throw new exception();
?>
When you execute the following code:
<?php
function testReturn() {
echo 'Executing testReturn()...';
include_once('return.php');
echo 'testReturn() executed normally.';
}
function testException() {
echo 'Executing testException()...';
include_once('exception.php');
echo 'testException() executed normally.';
}
testReturn();
echo "\n\n";
try {
testException();
}
catch (exception $e) {}
?>
...you get the following output as a result:
Executing testReturn()...testReturn() executed normally.
Executing testException()...
If you do use the exception method, make sure to put your function call in a try...catch block - having exceptions flying all over the place is bad for business.
Rock'n'roll like this :
index.php
function foo() {
return (include 'bar.php');
}
print_r(foo());
bar.php
echo "I will call the police";
return array('WAWAWA', 'BABABA');
output
I will call the police
Array
(
[0] => WAWAWA
[1] => BABABA
)
just show me how
like this :
return (include 'bar.php');
Have a good day !

Zend Framework view script, functions and variable scope

I am rather new to ZendFramework and am trying to figure this out. In my view script (index.phtml), I have this bit of code that says:
<?php
function getErrorString($element)
{
echo "<pre>";
print_r($this);
echo "</pre>";
$string = '';
if(!empty($this->error[$element]))
{
$string = $string.'<label class="error" for="'.$element.'" generated="true">';
foreach($this->error[$element] as $error)
{
$string = $string.$error;
}
$string = $string.'</label>';
}
return $string;
}
echo "<pre>";
print_r($this);
echo "</pre>";
getErrorString("blah");
die();
That gives me:
Fatal error: Using $this when not in object context in index.phtml on line XX
It seems to me that when you create a function within a view, you lose the $this variable. I did search around the net, and I can't see anyone else trying to achieve what I am doing (highly unlikely, maybe I'm searching it wrong).
With past experience developing other apps, I can't see a good reason why this function should be placed in a separate helper -> especially since this is the only place the function will ever be called.
Any ideas would be greatly appreciated.
Your function getErrorString() isn't an objectmethod of the Zend_View-Object.
It has it's own scope and couldn't reach $this.
The following code should work for you in the index.phtml
function getErrorString($viewObject, $element)
{
echo "<pre>";
print_r($viewObject);
echo "</pre>";
$string = '';
if(!empty($viewObject->error[$element]))
{
$string = $string.'<label class="error" for="'.$element.'" generated="true">';
foreach($viewObject->error[$element] as $error)
{
$string = $string.$error;
}
$string = $string.'</label>';
}
return $string;
}
echo "<pre>";
print_r($this);
echo "</pre>";
getErrorString($this,"blah");
die();
The last use of "$this" variable is probably the main reason for showing the fatal error. It's quite justified because of the fact that you cannot write anything else in the class definition, except defining methods & properties with respect to that class.
Also if you are creating any function in a view page, then within that function the "$this" variable is not accessible by default. So you will have to make that "$this" variable go global or you need to print the required part, related to "$this" variable, outside the function definition.
echo "<pre>";
print_r($this);
echo "</pre>";
So when you are writing the above code in the function definition, the PHP Parser is unable to find any object context for this "$this" variable. It's not that you are losing that "$this" variable, but it will not be accessible, but to the missing logic.
Hope it helps.

Categories