Working with variables

Variables in PHP are non-typed. A variable can thus hold any possible type: an integer, string, a floating point number, and even an object or an array. C++ on the other hand is a typed language. In C++ an integer variable always has a numeric value, and a string variable always hold a string value.

When you mix native code and PHP code, you will need to convert the non-typed PHP variables into native variables, and the other way round: convert native variables back into non-typed PHP variables. The PHP-CPP library offers the Php::Value class that makes this a very simple task.

Zval's

But we start with sharing one of our frustrations. If you have ever spent time on writing PHP extensions in plain C, or if you've ever read something about the internals of PHP, you must have heard about zval's. A zval is a C structure in which PHP variables are stored. Internally, this zval keeps a refcount, a union with the possible types and a number of other members too. Every time that you access such a zval, make a copy of it, or write to it, you must break your head to correctly update the refcount, and/or split the zval into different zvals, explicitly call copy constructors, allocate or free memory (using special memory allocation routines), or choose not to do this and leave the zval alone.

This all is crazy difficult and a big source for mistakes and all sorts of bugs.

And to make things even worse, there are literally hundreds of different undocumented (!) macro's and functions in the Zend engine that can manipulate these zval variables. There are special macro's that work on zval's, macro's for pointers-to-zval's, macro's for pointer-to-pointer-to-zval's and even macro's that deal with pointer-to-pointer-to-pointer-to-zval's.

Every single PHP module, every PHP extension, and every built-in PHP function is busy manipulating these zval structures. It is a big surprise that nobody ever took the time to wrap such a zval in a simple C++ class that does all this administration for you. C++ is such a nice language with constructors, destructors, casting operators and operator overloading that can encapsulate all this complicated zval handling.

And that is exactly what we did with PHP-CPP. We have introduced the Php::Value object with a very simple interface, that takes away all the problems of zval handling. Internally, the Php::Value object is a wrapper around a zval variable, but it completely hides the complexity of zval handling.

So, everything that you always wanted to ask about the internals of PHP, but were afraid to ask: just forget about it. Sit back and relax, and take a look how simple life is with PHP-CPP.

Scalar variables

The Php::Value object can be used to store scalar variables. Scalar variables are variables like integers, doubles, strings, booleans and null values. To create such a scalar variable, just assign it to a Php::Value object.


Php::Value value1 = 1234;
Php::Value value2 = "this is a string";
Php::Value value3 = std::string("another string");
Php::Value value4 = nullptr;
Php::Value value5 = 123.45;
Php::Value value6 = true;

The Php::Value class has casting operators to cast the object to almost every thinkable native type. When you have access to a Php::Value object, but want to store it in a (much faster) native variable, you can simply assign it.


void myFunction(const Php::Value &value)
{
    int value1 = value;
    std::string value2 = value;
    double value3 = value;
    bool value4 = value;
}

If the Php::Value object holds an object, and you cast it to a string, the __toString() method of the object gets called, exactly what would happen if you had casted the variable to a string in a PHP script.

Many different operators are overloaded too so that you can use a Php::Value object directly in arithmetric operations, compare it with other variables, or send it to an output stream.


void myFunction(Php::Value &value)
{
    value += 10;
    std::cout << value << std::endl;
    if (value == "some string")
    {
        
    }
    
    int result = value - 8;
}

The Php::Value object has implicit constructors for most types. This means that every function that accepts a Php::Value as parameter can also be called with a native type, and in functions that should return a Php::Value you can simply specify a scalar return value - which will automatically be converted into a Php::Value object by the compiler.


Php::Value myFunction(const Php::Value &value)
{
    if (value == 12)
    {
        return "abc";
    }
    else if (value > 100)
    {
        return myFunction(12);
    }
    
    return nullptr;
}

As you can see in the examples, you can do almost anything with Php::Value objects. Internally it does all the zval manipulation, and sometimes that can become complicated, but for you, the extension programmer, there is nothing to worry about.

Arrays

PHP supports two array types: regular arrays (indexed by numbers) and associative arrays (indexed by strings). The Php::Value object supports arrays too. By using array access operators (square brackets) to assign values to a Php::Value object, you automatically turn it into an array.


// create a regular array
Php::Value array;
array[0] = "apple";
array[1] = "banana";
array[2] = "tomato";

// an initializer list can be used to create a filled array 
Php::Value filled({ "a", "b", "c", "d"});

// you can cast an array to a vector, template parameter can be
// any type that a Value object is compatible with (string, int, etc)
std::vector fruit = array;

// create an associative array
Php::Value assoc;
assoc["apple"] = "green";
assoc["banana"] = "yellow";
assoc["tomato"] = "green";

// the variables in an array do not all have to be of the same type
Php::Value assoc2;
assoc2["x"] = "info@example.com";
assoc2["y"] = nullptr;
assoc2["z"] = 123;

// nested arrays are possible too
Php::Value assoc2;
assoc2["x"] = "info@example.com";
assoc2["y"] = nullptr;
assoc2["z"][0] = "a";
assoc2["z"][1] = "b";
assoc2["z"][2] = "c";

// assoc arrays can be cast to a map, indexed by string
std::map map = assoc2;

Reading from arrays is just as simple. You can use the array access operators (square brackets) for this too.


Php::Value array;
array["x"] = 10;
array["y"] = 20;

std::cout << array["x"] << std::endl;
std::cout << array["y"] << std::endl;

There also is a special Php::Array class. This is an extended Php::Value class that, when constructed, immediately starts as empty array (unlike Php::Value objects that by default construct to NULL values).


// create empty array
Php::Array array1;

// Php::Value is the base class, so you can assign Php::Array objects
Php::Value array2 = array1;

// impossible, a Php::Array must always be an array
array1 = 100;

@todo explain how to iterate over arrays

Objects

Just like the Php::Array class that is an extended Php::Value that initializes to an empty array, there also is a Php::Object class that becomes an object when constructed. By default this is an instance of stdClass - PHP's most simple class.


// create empty object of type stdClass
Php::Object object;

// Php::Value is the base class, so you can assign Php::Object objects
Php::Value value = object;

// impossible, a Php::Object must always be an object
object = "test";

// object properties can be accessed with square brackets
object["property1"] = "value1";
object["property2"] = "value2";

// to create an object of a different type, pass in the class name 
// to the constructor with optional constructor parameters
object = Php::Object("DateTime", "now");

// methods can be called with the call() method
std::cout << object.call("format", "Y-m-d H:i:s") << std::endl;

// all these methods can be called on a Php::Value object too
Php::Value value = Php::Object("DateTime", "now");
std::cout << value.call("format", "Y-m-d H:i:s") << std::endl;

Functions

When a Php::Value object holds a callable, you can use the () operator to call this function or method.


// create a string with a function name
Php::Value date = "date";

// "date" is a built-in PHP function and thus can it be called
std::cout << date("Y-m-d H:i:s") << std::endl;

// create a date-time object
Php::Object now = Php::Object("DateTime","now");

// create an array with two members, the datetime object
// and the name of a method
Php::Array array();
array[0] = now;
array[1] = "format";

// an array with two members can be called too, the first
// member is seen as the object, and the second as the
// name of the method
std::cout << array("Y-m-d H:i:s") << std::endl;

Global variables

To read or update global PHP variables, you can use the Php::GLOBALS variable. This variable works more or less the same as the $_GLOBALS variable in a PHP script.


// set a global PHP variable
Php::GLOBALS["a"] = 12345;

// global variables can be of any type
Php::GLOBALS["b"] = Php::Array({1,2,3,4});

// nested calls are (of course) supported
Php::GLOBALS["b"][4] = 5;

// and global variables can also be read
std::cout << Php::GLOBALS["b"] << std::endl;

Unlike PHP scripts, that handles only single pageviews, an extension is used to handle multiple pageviews after each other. This means that when you use global C++ (!) variables in your extension, that these variables are not set back to their initial value in between the pageviews. The Php::GLOBALS variable however, is always re-initialized at the beginning of every new pageview.

You can read more about this in the article about the the extension callbacks.