### 进入例子目录
“`
cd $odp_root/php/phplib/protobuf/example
“`
### 编写proto文件
`foo.proto`文件如下:
message Foo
{
required int32 bar = 1;
optional string baz = 2;
repeated float spam = 3;
}
### 编译proto文件
“`
php ../protoc-php.php foo.proto
“`
编译后,可生成一个`pb_proto_foo.php`文件
### 编写用户代码
`example.php`文件如下
<?php
require_once ‘pb_proto_foo.php’;
$foo = new Foo();
$foo->setBar(1);
$foo->setBaz(‘two’);
$foo->appendSpam(3.0);
$foo->appendSpam(4.0);
$packed = $foo->serializeToString(); #打包
$foo->clear();
try {
$foo->parseFromString($packed); #解包
} catch (Exception $ex) {
die(‘Upss.. there is a bug in this example’);
}
$foo->dump();
?>
然后执行`php example.php`,预期结果:
Foo {
1: bar => 1
2: baz => ‘two’
3: spam(2) =>
[0] => 3
[1] => 4
}