我在Laravel家庭项目中使用phpserial,通过串行USB端口将灯光设置输出到DMX灯光控制器。如果我声明一个受保护的字符串,这可以正常工作,但是当我尝试在类中设置一个const时,这不起作用。
如何创建一个由3个二进制字节(1,0,1)组成的const?
代码段:
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use PhpSerial;
class SerialCommsServiceProvider extends ServiceProvider
{
/**
* The Serial Interface
*/
protected $serial;
CONST INITLIGHTS = chr(1) . chr(0) . chr(1); // THIS FAILS BUT CONST MUST BE DECLARED AT TOP SCOPE IN CLASS
protected $initLights;
/**
* Create a new serial interface
*
*/
public function __construct()
{
$this->serial = new PhpSerial();
//Get environmental config or if not available, use the default (second parameter_
$this->serial->deviceSet(env('SERIAL_DEVICE','USB0'));
$this->serial->confBaudRate(env('SERIAL_BAUD_RATE','9600'));
$this->serial->confParity(env('SERIAL_PARITY','none'));
$this->serial->confCharacterLength(env('SERIAL_CHARACTER_LENGTH',8));
$this->serial->confStopBits(env('SERIAL_STOP_BITS',1));
$this->serial->confFlowControl(env('SERIAL_FLOW_CONTROL','none'));
if (env('APP_ENV') === 'production') {
// So now we need to open it
$this->serial->deviceOpen();
$this->initLights = chr(1) . chr(0) . chr(1); //THIS WORKS FINE, BUT AS THE INIT STRING IS A CONSTANT...
答案 0 :(得分:1)
PHP docs表示类常量必须为a constant expression, not (for example) a variable, a property, or a function call.
;虽然PHP 5.6在常量定义中添加了对基本表达式的支持,但它仍然不支持对函数的调用。
但是,您可以表达该字符序列而无需调用chr()
来执行此操作
CONST INITLIGHTS = "\x00\x01\x00";
所以不要使用变量,属性,函数调用甚至表达式,只需要一个字符串定义