Search code examples
phpprotocol-buffersgrpc

var_dump() does not work on instances of gRPC Protobuf classes


Here's my .proto file:

message HelloReply {
  string message = 1;
}

Here's the output php from the protoc run with grpc_php_plugin:

<?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;
    }

}

Here's a snipit from my code:

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

Here's the output:

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

Why does var_dump not give me the value of "name" that is stored in the 'HelloRequest' object? How can I output all the properties and their values of an instance of a gRPC generated class? What is causing the properties of instances of classes that extend the gRPC 'Message' to be hidden?

I have tried type casting:

$strvar = (string) $request;

causes the following error:

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

Solution

  • A workaround may be var_dump($request->serializeToJsonString())

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