用PHPCPP来开发PHP扩展是非常容易的,最主要的就是变量类型和PHP中的变量类型一毛一样,最重要的是写法也是一毛一样。
在PHP中,变量默认是没有类型的,我们赋给他整数,他就是整形,赋给他字符串他就是string,也就是说PHP中的变量类型是随着值来定义的。PHPCPP在这里也是做了很大的优化,实现了类型随值的类型来定义。
1Php::Value value1 = 1234; 2Php::Value value2 = "this is a string"; 3Php::Value value3 = std::string("another string"); 4Php::Value value4 = nullptr; 5Php::Value value5 = 123.45; 6Php::Value value6 = true;
其中Php::Value是PHPCPP定义一种类型,这个类型会进行隐式转换,就如同我们在PHP中用到的变量。
1void myFunction(const Php::Value &value) 2{ 3 int value1 = value;//这里的value就被隐式转换了,不然string怎么可能赋给int,C++中是绝对不允许的 4 std::string value2 = value;//这里又给转换成了string 5 double value3 = value; 6 bool value4 = value; 7}
PHPCPP中Php::Value是和PHP的变量类型对应的,所以你会定义PHP变量,很容易就能接受PHPCPP的变量定义方式。
PHPCPP中数组的定义,这里就不用过多介绍了,因为你是一个PHPER,所以你了解下面的含义吧。
1Php::Value array; 2array[0] = "apple"; 3array[1] = "banana"; 4array[2] = "tomato"; 5 6// an initializer list can be used to create a filled array 7Php::Value filled({ "a", "b", "c", "d"}); 8 9// you can cast an array to a vector, template parameter can be 10// any type that a Value object is compatible with (string, int, etc) 11std::vector<std::string> fruit = array; 12 13// create an associative array 14Php::Value assoc; 15assoc["apple"] = "green"; 16assoc["banana"] = "yellow"; 17assoc["tomato"] = "green"; 18 19// the variables in an array do not all have to be of the same type 20Php::Value assoc2; 21assoc2["x"] = "info@example.com"; 22assoc2["y"] = nullptr; 23assoc2["z"] = 123; 24 25// nested arrays are possible too 26Php::Value assoc2; 27assoc2["x"] = "info@example.com"; 28assoc2["y"] = nullptr; 29assoc2["z"][0] = "a"; 30assoc2["z"][1] = "b"; 31assoc2["z"][2] = "c";
只需要记住,在PHPCPP中定义变量给PHP中交互就定义为PHP::VALUE就可以了。