php8.5
Home/ Manual/ yac / yac/ Yac::add

Yac::add

PHP function Edit on GitHub ✎

(PECL yac >= 1.0.0)

Store a value without overwriting an existing one

Description

Yac::add(string|array $key, mixed $value, int $ttl = 0): bool
Yac::add(array $values, int $ttl = 0): bool

Stores a value in the cache. Unlike Yac::set, it does not overwrite an existing entry that is still valid; the store is rejected in that case.

Parameters

key

A string key, or an array of key => value pairs to store in one call.

value

The value to store. Every PHP type except resource can be stored. Only used in the single-key form; when key is an array, this argument is instead the optional ttl.

ttl

Time to live in seconds. 0 means the entry never expires by time.

Return Values

Returns true on success, false on failure. A store is also rejected (returning false) when the key already exists and has not expired.

Examples

Yac::add example

php
<?php
$yac = new Yac();

var_dump($yac->add("foo", "bar"));          // bool(true)
var_dump($yac->add("foo", "baz"));          // bool(false): "foo" already exists
?>

Adding an entry with a TTL

php
<?php
$yac = new Yac();

// ttl in seconds; 0 (the default) means the entry never expires
$yac->add("short-lived", "value", 5);
sleep(6);
var_dump($yac->get("short-lived"));        // bool(false): expired
?>

Adding multiple entries at once

php
<?php
$yac = new Yac();

// store several key => value pairs with one call, with a ttl
$yac->add(array("a" => 1, "b" => 2), 60);
?>

See Also

  • Yac::set
  • Yac::get
  • Yac::delete

Source: reference/yac/yac/add.xml · from the official PHP manual (php/doc-en)