企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] ## 概述 php 的构造函数与c++ 的构造函数不同 php的构造函数在调用时候,类已经初始化,而c++却并未初始化 ``` abstract class BASE { public function __construct() { $this->doSomething(); } public abstract function doSomething(); } class DERIVED extends BASE { public function doSomething() { echo ("doSomething()\n"); } } $d = new DERIVED(); ``` > 在 php 中上述运行可以,但在c++ 的构造时不能调用虚拟方法 ## 示例 ### hello world <details> <summary>main.cpp</summary> ``` #include <phpcpp.h> class Counter : public Php::Base { private: int _value = 0; public: Counter() = default; virtual ~Counter() = default; void __construct(Php::Parameters &params) { if (!params.empty()) _value = params[0]; } Php::Value increment() { return ++_value; } Php::Value decrement() { return --_value; } Php::Value value() const { return _value; } }; extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); Php::Class<Counter> counter("Counter"); counter.method<&Counter::__construct>("__construct"); counter.method<&Counter::increment>("increment"); counter.method<&Counter::decrement>("decrement"); counter.method<&Counter::value>("value"); myExtension.add(std::move(counter)); return myExtension; } } ``` </details> <br /> 示例 ``` <?php $counter = new Counter(10); $counter->increment(); echo($counter->value()."\n");// 11 ``` ### 设置__construct 为私有,会报错 在php 进行 new 时,会报错,因为__construct是私有方法 ``` counter.method<&Counter::__construct>("__construct", Php::Private); ``` ### __clone 克隆对象 如果php类不想被clone 1. 您可以从类中删除复制构造函数 2. 可以注册一个私有__clone()方法 ``` counter.method("__clone", Php::Private); ``` ### c++调用c++对象,返回给php 推荐使用`Php::Object()`好于`Php::Value()` <details> <summary>main.cpp</summary> ``` #include <phpcpp.h> class Counter : public Php::Base { private: int _value = 0; public: Counter(int value) : _value(value) {} virtual ~Counter() = default; void __construct() {} Php::Value value() const { return _value; } }; Php::Value createTimer() { return Php::Object("Counter", new Counter(100)); } extern "C" { PHPCPP_EXPORT void *get_module() { static Php::Extension myExtension("my_extension", "1.0"); Php::Class<Counter> counter("Counter"); counter.method<&Counter::__construct>("__construct", Php::Private); counter.method<&Counter::value>("value"); myExtension.add(std::move(counter)); myExtension.add("createTimer", createTimer); return myExtension; } } ``` </details> <br />