PHP-CPP是一個用於開發PHP擴展的C++庫。本節講解PHP函數形參相關的實現。php
有時候,咱們須要指定函數的形參是數組或者指定的,那麼在PHP-CPP裏是否能夠指定函數的參數類型呢?答案是能夠的。數組
示例:函數
/** * User: 公衆號: 飛鴻影的博客(fhyblog) * Date: 2018/7 */ #include <phpcpp.h> void example(Php::Parameters ¶ms) { } extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); myExtension.add<example>("example", { Php::ByVal("a", Php::Type::Numeric), Php::ByVal("b", "ExampleClass"), Php::ByVal("c", "OtherClass") }); return myExtension; } }
咱們使用Php::ByVal()
進行指定函數類型,示例裏分別指定爲Numeric
和自定義類類型。測試
咱們再看一下Php::ByVal()
原型:ui
/** * Constructor * @param name Name of the parameter * @param type Parameter type * @param required Is this parameter required? */ ByVal(const char *name, Php::Type type, bool required = true);
第一個參數a
、b
、c
能夠視爲佔位符,內部要用到,不重複便可。
第二個參數支持如下類型:this
Php::Type::Null Php::Type::Numeric Php::Type::Float Php::Type::Bool Php::Type::Array Php::Type::Object Php::Type::String Php::Type::Resource Php::Type::Constant Php::Type::ConstantArray Php::Type::Callable
這些類型其實就是PHP支持的變量類型。code
最後一個參數能夠用來設置參數是否可選,默認必選。若是將其設置爲true,則在沒有此參數的狀況下調用函數時,PHP將觸發錯誤。blog
咱們以sum_n
函數爲例:開發
extension.add<sum_n>("sum_n", { Php::ByVal("a", Php::Type::Numeric, true) });
若是使用的時候不給參數,就會PHP Warning:get
PHP Warning: sum_n() expects at least 1 parameter(s), 0 given in /media/d/work/php-ext/phpcpp/phpcpp_helloworld/test.php on line 4
Php::ByVal()
還有一種原型:
/** * Constructor * @param name Name of the parameter * @param classname Name of the class * @param nullable Can it be null? * @param required Is this parameter required? */ ByVal(const char *name, const char *classname, bool nullable = false, bool required = true);
多了個nullable
:是否能夠用NULL
來代替參數。好比:
extension.add<say_class>("say_class", { Php::ByVal("class_name", "Datetime", true, true) });
這個say_class
方法裏,咱們指定形參爲Datetime
類型,能夠使用NULL替代,參數必選。若是nullable
改成false,這時候就必須傳指定類型Datetime
了。
有時候咱們須要支持函數直接修改原來的變量值,就須要使用引用的方式傳參了。PHP-CPP也提供了Php::ByRef
進行支持。
/** * Constructor * @param name Name of the parameter * @param type Parameter type * @param required Is this parameter required? */ ByRef(const char *name, Php::Type type, bool required = true);
示例:
/** * User: 公衆號: 飛鴻影的博客(fhyblog) * Date: 2018/7 */ #include <phpcpp.h> void swap(Php::Parameters ¶ms) { Php::Value temp = params[0]; params[0] = params[1]; params[1] = temp; } extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); myExtension.add<swap>("swap", { Php::ByRef("a", Php::Type::Numeric), Php::ByRef("b", Php::Type::Numeric) }); return myExtension; } }
咱們使用test.php進行測試:
<?php // define two variables $a = 1; $b = 2; // 交換變量 swap($a, $b); // 下面使用錯誤,僅支持變量引用 //swap(10,20); //會觸發PHP Fatal error: Only variables can be passed by reference var_dump($a, $b); ?>
(未完待續)
想第一時間獲取最新動態,歡迎關注關注飛鴻影的博客(fhyblog)
,不按期爲您呈現技術乾貨。