JimFuqua February 2016

Call PHP static method from JavaScript without intermediary PHP script

PHP classes should normally be in a file by themselves. Static PHP methods can be called within PHP without instantiation of the class as below:

<?php

class TestClass
 {
   static function myStaticFunction()
     {
        return "The uninstantiated return value";
     }
 }

 echo TestClass::myStaticFunction();
 // echos "The uninstantiated return value"

It is easy to use a Javascript ajax call to a PHP script that instantiates a PHP class and runs a class method.

My question is: Is it possible to call a PHP static class method from Javascript using ajax thus eliminating the need for an intermediate PHP script or instantiation of the class, while not violating the PHP good practice of classes being in separate files all to themselves.

I tried putting the call to the PHP static method in the class constructor and got an error message. Putting all of the functionality in the constructor would also defeat the utility of the class for other purposes.

If this is possible please show how one would call a static PHP class method using ajax without using an intermediary script. If this has been answered before please provide a link to the answer before closing this question as I have not found an answer directly on point.

If this is impossible, why is it that PHP can call a static class method without instantiation, but Javascript cannot do the same via ajax?

Answers


JimFuqua February 2016

See: AJAX request and PHP class functions for a similar, but not identical, question with several answers.

It appears that PHP can call a static class function without instantiation of the class, but js ajax cannot do the same. At least, that is the consensus from most all of your answers.

Many people responded suggesting the intermediate script, but that was not the question. The question was how to avoid the intermediate script.

http://stackoverflow.com/users/1006348/rajesh saw the problem best in the other posting.

http://stackoverflow.com/users/1311025/tomas-prado suggested the best answer but discounted the value of the answer in the other posting. He suggested one intermediate script that can handle any ajax call that requires only instantiating one class and one class method with included data. I have not tried it, but I think that will work. No need for 50 intermediate scripts. Each ajax call will call the same PHP intermediate script. The data will name the class and the method and supply the remaining needed data. The universal intermediate script will parse out the class and method and send the data package there. The class method will be designed to ignore the first two fields in the data because they are only for routing info.

Thanks for all of the answers. If anyone has a better answer please let us all know.

jimfuqua

Post Status

Asked in February 2016
Viewed 1,329 times
Voted 5
Answered 1 times

Search




Leave an answer