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

Issue

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.

Solution

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();

Answered By – IMSoP

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published.