https://github.com/yurunsoft/php-macro
支持在 PHP 代码中使用类似 C/C++ 中的宏,进行代码预编译。可以方便兼容不同版本和环境下运行的 PHP 代码。
https://github.com/yurunsoft/php-macro
Last synced: about 1 year ago
JSON representation
支持在 PHP 代码中使用类似 C/C++ 中的宏,进行代码预编译。可以方便兼容不同版本和环境下运行的 PHP 代码。
- Host: GitHub
- URL: https://github.com/yurunsoft/php-macro
- Owner: Yurunsoft
- License: mit
- Created: 2021-11-27T02:05:10.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2022-11-15T08:39:14.000Z (over 3 years ago)
- Last Synced: 2025-04-12T21:46:42.571Z (about 1 year ago)
- Language: PHP
- Homepage:
- Size: 43 KB
- Stars: 8
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# php-macro
[](https://packagist.org/packages/yurunsoft/macro)
[](https://github.com/Yurunsoft/php-macro/actions/workflows/test.yml)
[](https://secure.php.net/)
## 介绍
支持在 PHP 代码中使用类似 C/C++ 中的宏,进行代码预编译。可以方便兼容不同版本和环境下运行的 PHP 代码。
## 使用
安装:`composer require yurunsoft/macro`
### 支持的宏
#### 常量
**宏:**`#define`、`#const`、`#ifdef`、`#ifndef`
**例子:**
```php
#ifndef IN_SWOOLE
# define IN_SWOOLE extension_loaded('swoole')
#endif
#ifdef IN_SWOOLE
#if IN_SWOOLE
\Co\run(function(){
echo 'hello world';
});
#endif
#endif
```
> 注意:使用宏定义的常量,仅在生成代码时有效,运行时无效
#### 条件语句
**宏:**`#if`、`#else`、`#elif`、`#endif`
**例子:**
```php
=')
function test(): string|false
#else
/**
* @return string|false
*/
function test()
#endif
{
return 'hello world';
}
```
PHP >= 8.0 环境下生成的代码:
```php
这个最为常用
#### convert
将带有宏的代码,转换为预编译后的 PHP 代码
`MacroParser::parse(string $content): string`
#### convertFile
将带有宏代码的文件,转换为预编译后的 PHP 代码并保存到目标文件。
方法返回值是预编译后的 PHP 代码。
`MacroParser::convertFile(string $srcFile, string $destFile = ''): string`
#### parse
将带有宏的代码,编译成预编译的 PHP 代码
`MacroParser::parse(string $content): string`
#### execParsedCode
执行预编译的 PHP 代码,返回预编译后的 PHP 代码
`MacroParser::execParsedCode(string $code): string`
## 注意事项
* 你的代码的 PHP 字符串中不能出现:``。如果有可以拆开使用拼接的方式
**例子:**
```php
'; // 错误的写法
echo '' . 'php echo "hello world"; ?' . '>'; // 正确的写法
```