var_dump()在gRPC Protobuf类的实例上不起作用

时间:2019-03-14 05:33:04

标签: php protocol-buffers grpc

这是我的.proto文件:

message HelloReply {
  string message = 1;
}

这是使用grpc_php_plugin运行的协议输出的php:

<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: helloworld.proto

namespace Helloworld;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

    /**
 * The request message containing the user's name.
 *
 * Generated from protobuf message <code>helloworld.HelloRequest</code>
 */
class HelloRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Generated from protobuf field <code>string name = 1;</code>
     */

    private $name = '';

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type string $name
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Helloworld::initOnce();
        parent::__construct($data);
    }

    /**
     * Generated from protobuf field <code>string name = 1;</code>
     * @return string
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * Generated from protobuf field <code>string name = 1;</code>
     * @param string $var
     * @return $this
     */
    public function setName($var)
    {
        GPBUtil::checkString($var, True);
        $this->name = $var;

        return $this;
    }

}

这是我代码中的一个小故事:

$name="test_name";
$request = new Helloworld\HelloRequest(array("name"=>$name));
echo "Name is " . $request->getName() . "\n";
var_dump($request);

以下是输出:

Name is test_name
object(Helloworld\HelloRequest)#3 (0) {
}

为什么var_dump不给我“ HelloRequest”对象中存储的“名称”值? 如何输出gRPC生成的类的实例的所有属性及其值? 是什么导致隐藏了扩展gRPC'Message'的类的实例的属性?

我尝试过类型转换:

$strvar = (string) $request;

导致以下错误:

PHP Recoverable fatal error:  Object of class Helloworld\HelloRequest could not be converted to string in /home/........./php/greeter_client.php on line 42

1 个答案:

答案 0 :(得分:1)

一种解决方法可能是 var_dump($request->serializeToJsonString())

https://github.com/protocolbuffers/protobuf/blob/master/php/src/Google/Protobuf/Internal/Message.php#L1489