类属性

最后更新于:2022-04-02 02:33:33

[TOC] ## 示例 ### 普通成员变量
main.cpp ``` #include class Example : public Php::Base { public: Example() = default; virtual ~Example() = default; void __construct() { Php::Value self(this); } }; extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); Php::Class example("Example"); example.method<&Example::__construct>("__construct"); // 设置元素值 example.property("property1", "xyz", Php::Public); myExtension.add(std::move(example)); return myExtension; } } ```

main.php ``` property1); $e->property1 = "new value1"; var_dump($e->property1); // new value1 ```

### 静态属性和类常量
main.cpp ``` #include class Example : public Php::Base { public: Example()=default; virtual ~Example()=default; }; extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); Php::Class example("Example"); // the Example class has a class constant example.property("MY_CONSTANT", "some value", Php::Const); // and a public static propertie example.property("my_property", "initial value", Php::Const | Php::Static); // add the class to the extension myExtension.add(std::move(example)); // return the extension return myExtension; } } ```

main.php ```
### 智能属性
main.cpp ``` #include class Example : public Php::Base { private: int _value = 0; public: Example() = default; virtual ~Example() = default; Php::Value getValue() const { return _value; } void setValue(const Php::Value &value) { _value = value; if (_value > 100) _value = 100; } }; extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); Php::Class example("Example"); // 对属性进行 读取与设置 example.property("value", &Example::getValue, &Example::setValue); myExtension.add(std::move(example)); return myExtension; } } ```

main.php ``` value="23"; var_dump($object->value); // 23 ```

';