1
0
mirror of https://github.com/danog/amp.git synced 2024-12-11 17:09:40 +01:00
amp/docs/utils/struct.md

48 lines
1.9 KiB
Markdown
Raw Normal View History

---
layout: docs
2017-05-26 21:13:34 +02:00
title: Struct
permalink: /utils/struct
---
2017-08-01 15:14:22 +02:00
A struct is a generic computer science term for an object composed of public properties. The `\Amp\Struct` trait
2017-03-19 00:47:13 +01:00
is intended to make using public properties a little safer by throwing an `\Error` when undefined properties
are attempted to be written or read.
PHP allows for dynamic creation of public properties. This can lead to insidious bugs created by typos related to
writing to and reading from public properties. One common solution to this problem is to make all properties private and
provide public setter and getter methods which control access to the underlying properties. However effective this
solution may be, it requires that additional code be written and subsequently tested for the setter and getter methods.
Let's try some examples with anonymous classes to demonstrate the advantages of using the `\Amp\Struct` trait. Running
the following code will not error; although, the typo will likely create some unexpected behavior:
```php
2017-03-19 21:03:33 +01:00
$obj = new class {
2017-03-19 00:47:13 +01:00
public $foo = null;
};
2017-03-19 21:03:33 +01:00
$obj->fooo = "bar";
2017-03-19 00:47:13 +01:00
```
2017-03-19 21:03:33 +01:00
If you were to access the `$foo` property of the `$obj` object after the above code, you might expect the value
2017-03-19 00:47:13 +01:00
to be `"bar"` when it would actually be `NULL`.
When a class uses the `\Amp\Struct` trait, an `\Error` will be thrown when attempting to access a property not defined
in the class definition. For example, the code below will throw an `\Error` with some context that attempts to help
diagnose the issue.
```php
2017-03-19 21:03:33 +01:00
$obj = new class {
use Amp\Struct;
2017-03-19 00:47:13 +01:00
public $foo = null;
};
2017-03-19 21:03:33 +01:00
$obj->fooo = "bar";
2017-03-19 00:47:13 +01:00
```
The message for the thrown `\Error` will be similar to:
*Uncaught Error: class@anonymous@php shell code0x10ee8005b property "fooo" does not exist ... did you mean "foo?"*
Although, an `\Error` being thrown in your code may cause some havoc, it will not allow for unpredictable
2017-03-19 21:03:33 +01:00
behavior caused by the use of properties which are not part of the class definition.