PHPcpp 变量和类型

 

 

    用PHPCPP来开发PHP扩展是非常容易的,最主要的就是变量类型和PHP中的变量类型一毛一样,最重要的是写法也是一毛一样。

    在PHP中,变量默认是没有类型的,我们赋给他整数,他就是整形,赋给他字符串他就是string,也就是说PHP中的变量类型是随着值来定义的。PHPCPP在这里也是做了很大的优化,实现了类型随值的类型来定义。

    

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;

    其中Php::Value是PHPCPP定义一种类型,这个类型会进行隐式转换,就如同我们在PHP中用到的变量。

void myFunction(const Php::Value &value)
{
    int value1 = value;//这里的value就被隐式转换了,不然string怎么可能赋给int,C++中是绝对不允许的
    std::string value2 = value;//这里又给转换成了string
    double value3 = value;
    bool value4 = value;
}

    PHPCPP中Php::Value是和PHP的变量类型对应的,所以你会定义PHP变量,很容易就能接受PHPCPP的变量定义方式。

PHPCPP中数组的定义,这里就不用过多介绍了,因为你是一个PHPER,所以你了解下面的含义吧。

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<std::string> 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";

    只需要记住,在PHPCPP中定义变量给PHP中交互就定义为PHP::VALUE就可以了。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部