Skip to main content
The PHP Protocol Buffers runtime (version 5.35-dev) is available as a pure PHP Composer package or as a native C extension via PECL. Both provide the same API and share generated code — you can switch implementations without regenerating.

Installation

1

Add the package to your project

composer require google/protobuf
Or add it manually to composer.json:
{
  "require": {
    "google/protobuf": "*"
  }
}
2

Install the bcmath extension

The pure PHP implementation requires bcmath for 64-bit integer support:
# Ubuntu/Debian
sudo apt-get install php-bcmath

Generating code

Install protoc and run it with --php_out to generate PHP classes:
protoc --php_out=out_dir addressbook.proto
For the addressbook.proto with package tutorial, this creates:
  • GPBMetadata/Addressbook.php — metadata for the descriptor pool
  • Tutorial/Person.php, Tutorial/AddressBook.php, etc. — message classes
  • Tutorial/Person/PhoneNumber.php, Tutorial/Person/PhoneType.php — nested types

Working with messages

Require the generated files and use the classes directly:
<?php
require_once 'vendor/autoload.php';
require_once 'GPBMetadata/Addressbook.php';
require_once 'Tutorial/Person.php';
require_once 'Tutorial/AddressBook.php';

// Create a person
$person = new Tutorial\Person();
$person->setId(1234);
$person->setName('Jane Doe');
$person->setEmail('[email protected]');

// Add a phone number
$phone = new Tutorial\Person\PhoneNumber();
$phone->setNumber('+1-555-0100');
$phone->setType(Tutorial\Person\PhoneType::MOBILE);
$person->setPhones([$phone]);

// Create an address book
$addressBook = new Tutorial\AddressBook();
$addressBook->setPeople([$person]);

Serializing and parsing

$serialized = $addressBook->serializeToString();
file_put_contents('addressbook.bin', $serialized);

Known limitations

The PHP implementation has the following known limitations:
  • No native support for well-known types.
  • No support for proto2.
  • No API for clear/copy operations on messages.
  • No streaming encode/decode API.
  • Map fields may not be garbage-collected if there is a cyclic reference.
  • Message names cannot be Empty.

Key API reference

Message methods

Every generated message class provides serializeToString(), mergeFromString($data), serializeToJsonString(), and mergeFromJsonString($json).

Field accessors

Fields are accessed via generated getters and setters: getName() / setName($value). Repeated fields return a RepeatedField object; map fields return a MapField.

Enums

Enum values are PHP integer constants. For example, Tutorial\Person\PhoneType::MOBILE is 0.

Descriptor pool

Metadata files (under GPBMetadata/) register message descriptors with the global descriptor pool when required. Always require them before using the message classes.

Build docs developers (and LLMs) love