I’ve been a pretty long time PHP developer, and I’m starting to hit some limitations within the language. So, with that being said, I figured the next step in my development cycle would be to move onto C++, and build out some extensions!
As I went through some standard “Hello World” like tutorials, everything seems to make sense for the most part. I built a fairly decent tic-tac-toe application, so I figured it was time to start diving into PECL and see how things were working. What I found however, kind of blows my mind.
Can anyone please explain both the purpose and reasoning to why something like this:
PHP_FUNCTION(helloWorld)
{
RETURN_STRING("Hello World");
}
isn’t more along the lines of this:
string helloWorld()
{
return "Hello World"
}
PHP_REGISTER_METHOD("helloWorld");
I’m not pretending that I know more than the people that created the language, and I’m not trying to stir up any trouble. It just seems (at least from a beginners perspective) that creating a PHP extension isn’t anything like writing a C++ program. It’s almost a different language completely, aside from some basic syntax rules.
Any help would be appreciated. Just a beginner trying to grow 🙂
PHP extension development does not differ that much from other C/C++ development. The only thing that is special is that you have to interface the PHP scripting world with your C/C++ functions. This task is not trivial, and here is where the weird macros such as PHP_FUNCTION are required.
For example, if you want to call a function “helloWorld” from PHP, the interpreter needs to lookup “helloWorld” and map it to a C function. This function needs to have a certain signature, that means it has to accept a certain set of parameters, and must return a certain value. This is not arbitrary and the interpreter cannot just call any C/C++ function.
This is just how low-level languages like C work, you cannot “inspect” what kind of arguments a function takes.
In particular, all values in the PHP interpreter are special structs that cannot be converted to C++ types. A PHP string is something different than a C++ std::string. The PHP API provides all kinds of tools to convert values, but you have to know how to use them.
Once you know how to write a C function that can be called from PHP, you are in “C/C++ world”, where you can call another C/C++ function and use C/C++ types. From here on, it’s just as writing pure C/C++ apps. Well, until you have to return values back to PHP world, where you have to use the PHP API tools again.
There are tools that can make your life easier, by helping in generating the required “glue code” to interface a scripting language such as PHP and “pure” C++ projects. Take a look at SWIG, which is probably the most prominent example.