Skip to content
Permalink
Browse files

Add docs for immutable ideas

  • Loading branch information...
muglug committed Sep 8, 2019
1 parent 78175c9 commit 5d08c47e4b1f1ec95cb3154223c814302e9736c5
Showing with 84 additions and 1 deletion.
  1. +84 −1 docs/annotating_code/supported_annotations.md
@@ -149,7 +149,7 @@ is not within the given namespace.

As other tools do not support `@psalm-internal`, it may only be used in conjunction with `@internal`.

```PHP
```php
namespace A\B {
/**
* @internal
@@ -174,6 +174,89 @@ namespace A\C {
}
}
```

### `@psalm-readonly` and `@readonly`

Used to annotate a property that can only be written to in its defining class's constructor.

```php
<?php
class B {
/** @readonly */
public string $s;
public function __construct(string $s) {
$this->s = $s;
}
}
$b = new B("hello");
echo $b->s;
$b->s = "boo"; // disallowed
```

### `@psalm-mutation-free`

Used to annotate a class method that does not mutate state, either internally or externally of the class's scope.

```php
class D {
private string $s;
public function __construct(string $s) {
$this->s = $s;
}
/**
* @psalm-mutation-free
*/
public function getShort() : string {
return substr($this->s, 0, 5);
}
/**
* @psalm-mutation-free
*/
public function getShortMutating() : string {
$this->s .= "hello"; // this is a bug
return substr($this->s, 0, 5);
}
}
```

### `@psalm-external-mutation-free`

Used to annotate a class method that does not mutate state, either internally or externally of the class's scope.

```php
class E {
private string $s;
public function __construct(string $s) {
$this->s = $s;
}
/**
* @psalm-external-mutation-free
*/
public function getShortMutating() : string {
$this->s .= "hello"; // this is fine
return substr($this->s, 0, 5);
}
/**
* @psalm-external-mutation-free
*/
public function save() : void {
file_put_contents("foo.txt", $this->s); // this is a bug
}
}
```

### `@psalm-immutable`

Used to annotate a class where every property is treated by consumers as `@psalm-readonly` and every method is treated as `@psalm-mutation-free`.

## Type Syntax

Psalm supports PHPDoc’s [type syntax](https://docs.phpdoc.org/guides/types.html), and also the [proposed PHPDoc PSR type syntax](https://github.com/php-fig/fig-standards/blob/master/proposed/phpdoc.md#appendix-a-types).

0 comments on commit 5d08c47

Please sign in to comment.
You can’t perform that action at this time.