diff --git a/.gitignore b/.gitignore index 1b49671..4600339 100644 --- a/.gitignore +++ b/.gitignore @@ -49,4 +49,5 @@ configure.in acinclude.m4 config.guess config.sub +/composer.lock diff --git a/docs/cn/php/inherit.md b/docs/cn/php/inherit.md index 175cafb..0be92de 100644 --- a/docs/cn/php/inherit.md +++ b/docs/cn/php/inherit.md @@ -14,7 +14,7 @@ composer require swoole/phpy ```php use phpy\PyClass; -#[parent('Animal', 'animal')] +#[Inherit('Animal', 'animal')] class Dog extends PyClass { protected string $weight; @@ -55,9 +55,9 @@ class Dog extends PyClass ``` - `PHP` 类必须要继承自 `PyClass` 基类 -- 使用 `#[parent('Animal', 'animal')]` 属性声明继承关系 +- 使用 `#[Inherit('Animal', 'animal')]` 属性声明继承关系 - 第一个参数为 `Python` 类名,第二个参数为 `Python` 包名 - - 支持多继承,多个 `#[parent]` 属性声明 + - 支持多继承,可添加多个 `#[Inherit]` 属性声明 - 在子类的构造方法必须执行父类的构造方法 `parent::__construct()`,否则会报错 ## 调用基类构造方法 @@ -96,11 +96,18 @@ $this->super()->speak('dog'); ## 多重继承 ```php -#[parent('Animal', 'animal')] -#[parent('Base', 'dog')] +#[Inherit('Animal', 'animal')] +#[Inherit('Base', 'dog')] class Dog extends PyClass {} ``` +等同于如下的 `Python` 代码: +```python +class Dog(Animal, Base): + pass +``` + + ## 传递对象到 `Python` 层 ```php $framework = PyCore::import('framework'); diff --git a/examples/class/Dog.php b/examples/class/Dog.php index 7a93807..e557d06 100644 --- a/examples/class/Dog.php +++ b/examples/class/Dog.php @@ -2,8 +2,11 @@ use phpy\PyClass; - -#[parent('Animal', 'animal')] +/** + * @property string $color + * @method get_age() + */ +#[Inherit('Animal', 'animal')] class Dog extends PyClass { function __construct(string $name, int $age) @@ -13,14 +16,14 @@ function __construct(string $name, int $age) $this->super()->__init__($name, $age); } - protected function test() + protected function test(): void { debug_print_backtrace(); } function speak(string $name): void { - echo "Dog $name, color: {$this->self()->color}, speak: wang wang wang\n"; + echo "Dog $name, color: {$this->color}, speak: wang wang wang\n"; $this->super()->speak('dog'); } } diff --git a/lib/phpy/Inherit.php b/lib/phpy/Inherit.php new file mode 100644 index 0000000..7434c3b --- /dev/null +++ b/lib/phpy/Inherit.php @@ -0,0 +1,13 @@ +_proxyClass = strtolower(str_replace('\\', '_', $class)); $this->_proxyFile = self::$_proxyPath . '/' . $this->_proxyClass . '.py'; - if (self::$_checkStat) { + $hasProxyFile = is_file($this->_proxyFile); + if ($hasProxyFile and self::$_checkStat) { $this->checkProxyFile(); } - - if (!is_file($this->_proxyFile)) { + if (!$hasProxyFile) { $this->makeProxy(); } + PyCore::import($this->_proxyClass)->{$this->_proxyClass}($this); } @@ -67,7 +68,10 @@ function __construct() private function makeProxy(): void { $ref = new ReflectionClass($this); - $refParents = $ref->getAttributes('parent'); + $refParents = $ref->getAttributes('inherit'); + if (empty($refParents)) { + $refParents = $ref->getAttributes('parent'); + } $import = ''; $parents = [];