Functions called on - php

Do functions parse the code when they are called or are they loaded even if the function isn't be called? Sorry if it seems like a newbie question, I'm just curious about this.
Thank you

They do not "process their code" until they are called. For example:
function my_function() {
return "Hello World";
}
The above will not execute until you call it:
echo my_function();
With that said, the code in your function still needs to be valid or it will cause errors.
You may want to read the User-defined functions or W3 Schools PHP Functions.
To keep the script from being executed when the page loads, you can
put it into a function. A function will be executed by a call to the function.

All code in a PHP file is parsed and converted to PHP bytecode before any of it is run.
For instance, a PHP file with a syntax error anywhere in it will fail to run at all, even if the syntax error isn't anywhere near the part that is being run.

Related

PHP How to make a function accessible with and without the call in the same file?

Sorry if my question is not clearly understandable, I don't know how to express well what I want to say in English.
This is not a problem with code per se, as it is working as shown, but mostly a doubt of the behaviour of PHP.
When I call a function from another php file, it seems to read the function itself i.e. function loademp(){}
however, if I access the file containing the function from an ajax, it seems to need a call to the function i.e loademp() to be in the same file.
Since I had this issue I ended having this code in order to make it work from both origins, with the call for the ajax inside an if condition, otherwise it would be called twice from the php file:
<?php
if ($_POST['runFunct']=="loademp"){ //call from ajax needs 'loademp()' to access the function;
loademp();
}
function loademp(){ //loaded from another file apparently.
try{
//PDO code
print_r(json_encode($results));
}catch(PDOException $e){
echo $e;
}
}
My other file just look like this:
require __DIR__.'loademp.php';
loademp();
Isn't there a more practical way to just use the code for both cases with no conditioning depending on the origin? Since I can't call a specific function from ajax without the use of POST variables, I guess this is the best case for it, but I would appreciate if you could point out the good practices about it.
I think your confusion here is between defining a function and executing a function.
To define a function, you write something like this:
function say_hello_world() {
echo "Hello, World!\n";
}
This doesn't cause anything to happen immediately, it just defines how to do something. In this case, it's basically like saying:
Whenever I ask you to "say hello world", output to the screen "Hello, World!\n"
To make something actually happen, you have to execute the function, which looks like this:
say_hello_world();
That's basically saying:
Do the actions I gave you for "say hello world"
In your example, your file 'loademp.php' defines a function called loademp - it says "whenever I ask you to 'loademp', here's what I want you to do". In your other file, you include that file, so the function is defined. Then, you run it with this line:
loademp();
An AJAX call is no different from any other page load, so you need to do the same thing there - first, define the function, or include the file that does; then, execute the function.
So, rather than calling loademp.php directly, you could call a PHP script like define_and_execute_loademp.php with exactly the lines you've mentioned:
require __DIR__.'loademp.php';
loademp();

check if functions referenced inside functions exist before commands are processed - PHP

I modified about 600 lines of code amongst over 5000 lines of code by updating function calls to match the new library I created for use with the script. I have spot some errors manually when updating before by hand, but I believe I overlooked some.
So far, the only way I can spot them is to run the code and have it crash when the error happens. This is a bad idea because such errors will happen before resources are freed.
Here's an example in code that explains my question:
Say I have mainline code (called index.php) that consists of this:
<?php
include "library.php";
$file=fopen("afile","w");
doWrite($file);
brokenFunction();
fclose($file);
exit();
?>
and say library.php contains only this:
<?php
function doWrite($file){
fwrite($file,"Test");
doNothing();
}
?>
Because brokenFunction(); and doNothing(); don't exist, an error is expected. Rather than PHP compile then execute code up until the first failing function call, how do I have PHP check to see if all referenced functions the mainline code links to exist before executing code?
So in my example, I expect an error and the code to stop compiling/executing at $file=fopen("afile","w"); because brokenFunction(); and doNothing(); don't exist.
How do I achieve this?
You can use the built-in function_exists() function:
if (!function_exists('brokenFunction')) {
throw new \Exception('brokenFunction is missing');
}
But this will only raise an error when executing the code.
Some tools like PHPStorm can check your code (without running it) and throw warnings if a function is missing.
Some other tools are listed in this (closed) SO question: Is there a static code analyzer [like Lint] for PHP files?.
The best way I've found to globally debug an environment without using #A.L's method and pasting a function_exists call before every edited line, is to use a PHP debugger of some sort, most likely built into an IDE that compares every function call line against a 'test compile' of your code and all included libraries to make sure the called function exists (and would likely underline it in red if it didn't). A PHP IDE like Aptana might be what you're looking for (especially if you see yourself having future updates to run as this solution will have the time overhead of installing/setting up Aptana).

Drupal PHP executing twice

After running a drush update on my drupal 7 site, the php code that I use to bring in user information for a form executes twice. This is a problem because I have created some functions in the php that get called so when it executes the PHP the second time it tries to re-declare the functions and I get errors like this:
PHP Fatal error: Cannot redeclare fooBar() (previously declared in [path_to_drupal7]/modules/php/php.module(80) : eval()'d code:3) in [path_to_drupal7]/modules/php/php.module(80) : eval()'d code on line 4
It doesn't matter what the function is called or what it does. In this example case this is the code:
<?php
function fooBar() {
print "foo bar";
}
fooBar();
?>
It also doesn't seem to matter what content type the page is (I my case I need it to bring user information into a form).
Why is Drupal executing the PHP twice? And more importantly, how can I keep it from doing so?
EDIT:
Drupal seems to be executing the php once for the trimmed version and once for full version and once for the full version. This is what I expect when I preview the post. I don't really care about the preview version so I would be happy to get rid of it. Why is Drupal executing the code twice when I view the page? (why is it running it for the trimmed version when I'm actually viewing the page?)
Something must be re-including/requiring the file containing this function or you have this function within a loop. Find that, or, wrap it with function_exists.
<?php
if (!function_exists('fooBar')) {
function fooBar() {
print "foo bar";
}
}
fooBar();
Like you said, the php you entered as input is being eval'd twice....once for the teaser, and once for the full body text.
Best practice: Don't define functions with eval. It can get messy fast.
Better practice: eval = evil. Don't use it.
In the time it takes to debug the problem, you could have written a very basic module that defines fooBar, then you can execute it from your PHP input field if you want.

Manually determine the last thing PHP does before it renders a page?

I'm trying to figure out the best way to unset a php session variable, after all pages have loaded and the page will be rendered to the browser. I have a page that includes & requires several pages to be rendered. I want to know if there is a built in php function that will tell php to do something right before the page is completed. Or what would the best way/practice to do this?
EDIT##
Here's what I added...
function unsetHIST_ID(){unset($_SESSION['Hist_CID']);}
register_shutdown_function('unsetHIST_ID');
Am not sure why you want this but if you want a function to be executed after script execution finishes or exit() is called then you should look at register_shutdown_function
Example
function shutdown() {
echo "Am dead anyway";
}
register_shutdown_function('shutdown');
echo "<pre>";
echo "Hello am Alive",PHP_EOL;
Output
Hello am Alive
Am dead anyway <---------------This would always run last
There's the .ini directive auto_append_file, which is parsed last by PHP if specified. It's basically treated as if you'd put require('somefile.php') as the very last command in a file yourself.
You need something like
register_shutdown_function ('my_atexit_function');
or maybe you can do this with
ob_start('content_handler');
The first function will be called immediately before exiting, which is not exactly what you asked for; and the second just before output, but that allows you to do something with an output that's already made static.
I'd go with register_shutdown_function though.

What is the difference between include() and calling a function in PHP?

What is the difference between include() and calling a function in PHP?
For example :
1-
<?php
$foo = '<p>bar</p>';
return $foo;
?>
<html><body><?php echo $foo; ?></body></html>
2-insert above php code in a php file and include()
thanks in advance
include() simply takes the full contents of the file and inserts it in, replacing the include() with the contents of the file.
If you have HTML in the included file, it will be output. If you only have PHP in it, the PHP will be run.
To call a function, the function must be available. If the function is in another file, you will still need to include() or require() that file to have it available.
Generally, including is used to get a set of functions or objects into your running script, so that they can be used, although it can also be used as a standalone page or some bit of HTML, like you posted. In reality, it depends on whether you'd rather have another function on the same script or in a remote script, for aesthetics or organization, whatever your reason.
Functions will usually run a bit faster, as server response time and parsing time may make the include function run a bit slower, but for all intents and purposes you wont notice much. Most of the lag will be due to the fact that a local function will be executed with the page, whereas the include function must execute the page, load another page, and then execute that page as well. If that makes sense.
Just as an addition to the existing answers, you can also do this:
sample.php:
<?php
$foo = include('include_with_return_value.php');
?>
<html><body><?php echo $foo; ?></body></html>
and include_with_return_value.php:
<?php
return '<p>bar</p>';
So, include() files can also have a return value, just like functions.

Categories