code
stringlengths
2.5k
150k
kind
stringclasses
1 value
php dio_stat dio\_stat ========= (PHP 4 >= 4.2.0, PHP 5 < 5.1.0) dio\_stat — Gets stat information about the file descriptor fd ### Description ``` dio_stat(resource $fd): array ``` **dio\_stat()** returns information about the given file descriptor. ### Parameters `fd` The file descriptor returned by [dio\_open()](function.dio-open). ### Return Values Returns an associative array with the following keys: * "device" - device * "inode" - inode * "mode" - mode * "nlink" - number of hard links * "uid" - user id * "gid" - group id * "device\_type" - device type (if inode device) * "size" - total size in bytes * "blocksize" - blocksize * "blocks" - number of blocks allocated * "atime" - time of last access * "mtime" - time of last modification * "ctime" - time of last change On error **dio\_stat()** returns **`null`**. php Collator::getLocale Collator::getLocale =================== collator\_get\_locale ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Collator::getLocale -- collator\_get\_locale — Get the locale name of the collator ### Description Object-oriented style ``` public Collator::getLocale(int $type): string|false ``` Procedural style ``` collator_get_locale(Collator $object, int $type): string|false ``` Get collector locale name. ### Parameters `object` [Collator](class.collator) object. `type` You can choose between valid and actual locale ( **`Locale::VALID_LOCALE`** and **`Locale::ACTUAL_LOCALE`**, respectively). ### Return Values Real locale name from which the collation data comes. If the collator was instantiated from rules or an error occurred, returns **`false`**. ### Examples **Example #1 **collator\_get\_locale()** example** ``` <?php $coll    = collator_create( 'en_US_California' ); $res_val = collator_get_locale( $coll, Locale::VALID_LOCALE ); $res_act = collator_get_locale( $coll, Locale::ACTUAL_LOCALE ); printf( "Valid locale name: %s\nActual locale name: %s\n",          $res_val, $res_act ); ?> ``` The above example will output: ``` Requested locale name: en_US_California Valid locale name: en_US Actual locale name: en ``` ### See Also * [collator\_create()](collator.create) - Create a collator php Transliterator::listIDs Transliterator::listIDs ======================= transliterator\_list\_ids ========================= (PHP 5 >= 5.4.0, PHP 7, PHP 8, PECL intl >= 2.0.0) Transliterator::listIDs -- transliterator\_list\_ids — Get transliterator IDs ### Description Object-oriented style ``` public static Transliterator::listIDs(): array|false ``` Procedural style ``` transliterator_list_ids(): array|false ``` Returns an array with the registered transliterator IDs. ### Parameters This function has no parameters. ### Return Values An array of registered transliterator IDs on success, or **`false`** on failure. ### Examples **Example #1 Retrieving the registered transliterator IDs** ``` <?php print_r(Transliterator::listIDs()); ?> ``` The above example will output something similar to: ``` Array ( [0] => ASCII-Latin [1] => Accents-Any [2] => Amharic-Latin/BGN [3] => Any-Accents [4] => Any-Publishing ... [650] => Any-ps_Latn/BGN [651] => Any-tk/BGN [652] => Any-ch_FONIPA [653] => Any-cs_FONIPA [654] => Any-cy_FONIPA ) ``` ### See Also * [Transliterator::getErrorMessage()](transliterator.geterrormessage) - Get last error message * [Transliterator::transliterate()](transliterator.transliterate) - Transliterate a string php feof feof ==== (PHP 4, PHP 5, PHP 7, PHP 8) feof — Tests for end-of-file on a file pointer ### Description ``` feof(resource $stream): bool ``` Tests for end-of-file on a file pointer. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns **`true`** if the file pointer is at EOF or an error occurs (including socket timeout); otherwise returns **`false`**. ### Notes **Warning** If a connection opened by [fsockopen()](function.fsockopen) wasn't closed by the server, **feof()** will hang. To workaround this, see below example: **Example #1 Handling timeouts with **feof()**** ``` <?php function safe_feof($fp, &$start = NULL) {  $start = microtime(true);  return feof($fp); } /* Assuming $fp is previously opened by fsockopen() */ $start = NULL; $timeout = ini_get('default_socket_timeout'); while(!safe_feof($fp, $start) && (microtime(true) - $start) < $timeout) {  /* Handle */ } ?> ``` **Warning** If the passed file pointer is not valid you may get an infinite loop, because **feof()** fails to return **`true`**. **Example #2 **feof()** example with an invalid file pointer** ``` <?php // if file can not be read or doesn't exist fopen function returns FALSE $file = @fopen("no_such_file", "r"); // FALSE from fopen will issue warning and result in infinite loop here while (!feof($file)) { } fclose($file); ?> ``` php EventUtil::getSocketName EventUtil::getSocketName ======================== (PECL event >= 1.5.0) EventUtil::getSocketName — Retreives the current address to which the socket is bound ### Description ``` public static EventUtil::getSocketName( mixed $socket , string &$address , mixed &$port = ?): bool ``` Retreives the current address to which the `socket` is bound. ### Parameters `socket` Socket resource, stream or a file descriptor of a socket. `address` Output parameter. IP-address, or the UNIX domain socket path depending on the socket address family. `port` Output parameter. The port the socket is bound to. Has no meaning for UNIX domain sockets. ### Return Values Returns **`true`** on success or **`false`** on failure. php Event::delSignal Event::delSignal ================ (PECL event >= 1.2.6-beta) Event::delSignal — Alias of [Event::del()](event.del) ### Description This method is an alias of: [Event::del()](event.del) php Componere\Method::__construct Componere\Method::\_\_construct =============================== (Componere 2 >= 2.1.0) Componere\Method::\_\_construct — Method Construction ### Description public **Componere\Method::\_\_construct**([Closure](class.closure) `$closure`) ### Parameters `closure` php None Enumeration constants --------------------- Enumerations may include constants, which may be public, private, or protected, although in practice private and protected are equivalent as inheritance is not allowed. An enum constant may refer to an enum case: ``` <?php enum Size {     case Small;     case Medium;     case Large;     public const Huge = self::Large; } ?> ``` php socket_set_blocking socket\_set\_blocking ===================== (PHP 4, PHP 5, PHP 7, PHP 8) socket\_set\_blocking — Alias of [stream\_set\_blocking()](function.stream-set-blocking) ### Description This function is an alias of: [stream\_set\_blocking()](function.stream-set-blocking). php xhprof_disable xhprof\_disable =============== (PECL xhprof >= 0.9.0) xhprof\_disable — Stops xhprof profiler ### Description ``` xhprof_disable(): array ``` Stops the profiler, and returns xhprof data from the run. ### Parameters This function has no parameters. ### Return Values An array of xhprof data, from the run. ### Examples **Example #1 **xhprof\_disable()** example** ``` <?php xhprof_enable(); $foo = strlen("foo bar"); $xhprof_data = xhprof_disable(); print_r($xhprof_data); ?> ``` The above example will output something similar to: ``` Array ( [main()==>strlen] => Array ( [ct] => 1 [wt] => 279 ) [main()==>xhprof_disable] => Array ( [ct] => 1 [wt] => 9 ) [main()] => Array ( [ct] => 1 [wt] => 610 ) ) ``` php unlink unlink ====== (PHP 4, PHP 5, PHP 7, PHP 8) unlink — Deletes a file ### Description ``` unlink(string $filename, ?resource $context = null): bool ``` Deletes `filename`. Similar to the Unix C unlink() function. An **`E_WARNING`** level error will be generated on failure. ### Parameters `filename` Path to the file. If the file is a symlink, the symlink will be deleted. On Windows, to delete a symlink to a directory, [rmdir()](function.rmdir) has to be used instead. `context` A [context stream](https://www.php.net/manual/en/stream.contexts.php) resource. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | On Windows, it is now possible to **unlink()** files with handles in use, while formerly that would fail. However, it is still not possible to re-create the unlinked file, until all handles to it have been closed. | ### Examples **Example #1 Basic **unlink()** usage** ``` <?php $fh = fopen('test.html', 'a'); fwrite($fh, '<h1>Hello world!</h1>'); fclose($fh); unlink('test.html'); ?> ``` ### See Also * [rmdir()](function.rmdir) - Removes directory php stats_dens_cauchy stats\_dens\_cauchy =================== (PECL stats >= 1.0.0) stats\_dens\_cauchy — Probability density function of the Cauchy distribution ### Description ``` stats_dens_cauchy(float $x, float $ave, float $stdev): float ``` Returns the probability density at `x`, where the random variable follows the Cauchy distribution whose location and scale are `ave` and `stdev`, respectively. ### Parameters `x` The value at which the probability density is calculated `ave` The location parameter of the distribution `stdev` The scale parameter of the distribution ### Return Values The probability density at `x` or **`false`** for failure. php SyncSharedMemory::__construct SyncSharedMemory::\_\_construct =============================== (PECL sync >= 1.1.0) SyncSharedMemory::\_\_construct — Constructs a new SyncSharedMemory object ### Description ``` public SyncSharedMemory::__construct(string $name, int $size) ``` Constructs a named shared memory object. ### Parameters `name` The name of the shared memory object. > > **Note**: > > > If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message. > > `size` The size, in bytes, of shared memory to reserve. > > **Note**: > > > The amount of memory cannot be resized later. Request sufficient storage up front. > > ### Return Values The new [SyncSharedMemory](class.syncsharedmemory) object. ### Errors/Exceptions An exception is thrown if the shared memory object cannot be created or opened. ### Examples **Example #1 **SyncSharedMemory::\_\_construct()** example** ``` <?php // You will probably need to protect shared memory with other synchronization objects. // Shared memory goes away when the last reference to it disappears. $mem = new SyncSharedMemory("AppReportName", 1024); if ($mem->first()) {     // Do first time initialization work here. } $result = $mem->write(json_encode(array("name" => "my_report.txt"))); ?> ``` ### See Also * [SyncSharedMemory::first()](syncsharedmemory.first) - Check to see if the object is the first instance system-wide of named shared memory * [SyncSharedMemory::size()](syncsharedmemory.size) - Returns the size of the named shared memory * [SyncSharedMemory::write()](syncsharedmemory.write) - Copy data to named shared memory * [SyncSharedMemory::read()](syncsharedmemory.read) - Copy data from named shared memory php ldap_first_attribute ldap\_first\_attribute ====================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_first\_attribute — Return first attribute ### Description ``` ldap_first_attribute(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false ``` Gets the first attribute in the given entry. Remaining attributes are retrieved by calling [ldap\_next\_attribute()](function.ldap-next-attribute) successively. Similar to reading entries, attributes are also read one by one from a particular entry. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `entry` An [LDAP\ResultEntry](class.ldap-result-entry) instance. ### Return Values Returns the first attribute in the entry on success and **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | The unused third parameter `ber_identifier` is no longer accepted. | ### See Also * [ldap\_next\_attribute()](function.ldap-next-attribute) - Get the next attribute in result * [ldap\_get\_attributes()](function.ldap-get-attributes) - Get attributes from a search result entry php sodium_crypto_box_seal sodium\_crypto\_box\_seal ========================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_box\_seal — Anonymous public-key encryption ### Description ``` sodium_crypto_box_seal(string $message, string $public_key): string ``` Encrypt a message such that only the recipient can decrypt it. Unlike with [sodium\_crypto\_box()](function.sodium-crypto-box), you only need to know the recipient's public key to use **sodium\_crypto\_box\_seal()**. One consequence of this convenience, however, is that the ciphertext isn't bound to a static public key, and is therefore not authenticated. Hence, anonymous public-key encryption. **sodium\_crypto\_box\_seal()** still provides ciphertext integrity. Just not sender identity authentication. If you also need sender authentication, the [sodium\_crypto\_sign()](function.sodium-crypto-sign) functions are likely the best place to start. ### Parameters `message` The message to encrypt. `public_key` The public key that corresponds to the only key that can decrypt the message. ### Return Values A ciphertext string in the format of (one-time public key, encrypted message, authentication tag). ### Examples **Example #1 **sodium\_crypto\_box\_seal()** example** ``` <?php $keypair = sodium_crypto_box_keypair(); $public_key = sodium_crypto_box_publickey($keypair); // Obfuscated plaintext to make the example more fun $plaintext_b64 = "V3JpdGluZyBzb2Z0d2FyZSBpbiBQSFAgY2FuIGJlIGEgZGVsaWdodCE="; $decoded_plaintext = sodium_base642bin($plaintext_b64, SODIUM_BASE64_VARIANT_ORIGINAL); $sealed = sodium_crypto_box_seal($decoded_plaintext, $public_key); var_dump(base64_encode($sealed)); $opened = sodium_crypto_box_seal_open($sealed, $keypair); var_dump($opened); ?> ``` The above example will output something similar to: ``` string(120) "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw=" string(41) "Writing software in PHP can be a delight!" ``` php ldap_err2str ldap\_err2str ============= (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_err2str — Convert LDAP error number into string error message ### Description ``` ldap_err2str(int $errno): string ``` Returns the string error message explaining the error number `errno`. While LDAP errno numbers are standardized, different libraries return different or even localized textual error messages. Never check for a specific error message text, but always use an error number to check. ### Parameters `errno` The error number. ### Return Values Returns the error message, as a string. ### Examples **Example #1 Enumerating all LDAP error messages** ``` <?php   for ($i=0; $i<100; $i++) {     printf("Error $i: %s<br />\n", ldap_err2str($i));   } ?> ``` ### See Also * [ldap\_errno()](function.ldap-errno) - Return the LDAP error number of the last LDAP command * [ldap\_error()](function.ldap-error) - Return the LDAP error message of the last LDAP command php readline_write_history readline\_write\_history ======================== (PHP 4, PHP 5, PHP 7, PHP 8) readline\_write\_history — Writes the history ### Description ``` readline_write_history(?string $filename = null): bool ``` This function writes the command history to a file. ### Parameters `filename` Path to the saved file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `filename` is nullable now. | php Imagick::textureImage Imagick::textureImage ===================== (PECL imagick 2, PECL imagick 3) Imagick::textureImage — Repeatedly tiles the texture image ### Description ``` Imagick::textureImage(Imagick $texture_wand): Imagick ``` Repeatedly tiles the texture image across and down the image canvas. ### Parameters `texture_wand` Imagick object to use as texture image ### Return Values Returns a new Imagick object that has the repeated texture applied. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::textureImage()**** ``` <?php function textureImage($imagePath) {     $image = new \Imagick();     $image->newImage(640, 480, new \ImagickPixel('pink'));     $image->setImageFormat("jpg");     $texture = new \Imagick(realpath($imagePath));     $texture->scaleimage($image->getimagewidth() / 4, $image->getimageheight() / 4);     $image = $image->textureImage($texture);     header("Content-Type: image/jpg");     echo $image; } ?> ``` php Zookeeper::isRecoverable Zookeeper::isRecoverable ======================== (PECL zookeeper >= 0.1.0) Zookeeper::isRecoverable — Checks if the current zookeeper connection state can be recovered ### Description ``` public Zookeeper::isRecoverable(): bool ``` The application must close the handle and try to reconnect. ### Parameters This function has no parameters. ### Return Values Returns true/false on success, and false on failure. ### Errors/Exceptions This method emits PHP error/warning when operation fails. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### See Also * [Zookeeper::\_\_construct()](zookeeper.construct) - Create a handle to used communicate with zookeeper * [Zookeeper::connect()](zookeeper.connect) - Create a handle to used communicate with zookeeper * [Zookeeper::getClientId()](zookeeper.getclientid) - Return the client session id, only valid if the connections is currently connected (ie. last watcher state is ZOO\_CONNECTED\_STATE) * [ZooKeeper States](class.zookeeper#zookeeper.class.constants.states) * [ZookeeperException](class.zookeeperexception) php IntlTimeZone::useDaylightTime IntlTimeZone::useDaylightTime ============================= intltz\_use\_daylight\_time =========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::useDaylightTime -- intltz\_use\_daylight\_time — Check if this time zone uses daylight savings time ### Description Object-oriented style (method): ``` public IntlTimeZone::useDaylightTime(): bool ``` Procedural style: ``` intltz_use_daylight_time(IntlTimeZone $timezone): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values
programming_docs
php uopz_get_hook uopz\_get\_hook =============== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_get\_hook — Gets previously set hook on function or method ### Description ``` uopz_get_hook(string $function): Closure ``` ``` uopz_get_hook(string $class, string $function): Closure ``` Gets the previously set hook on a function or method. ### Parameters `class` The name of the class. `function` The name of the function or method. ### Return Values Returns the previously set hook on a function or method, or **`null`** if no hook has been set. ### Examples **Example #1 Basic **uopz\_get\_hook()** Usage** ``` <?php function foo() {     echo 'foo'; } uopz_set_hook('foo', function () {echo 'bar';}); var_dump(uopz_get_hook('foo')); ?> ``` The above example will output something similar to: ``` object(Closure)#2 (0) { } ``` ### See Also * [uopz\_set\_hook()](function.uopz-set-hook) - Sets hook to execute when entering a function or method * [uopz\_unset\_hook()](function.uopz-unset-hook) - Removes previously set hook on function or method php CachingIterator::offsetSet CachingIterator::offsetSet ========================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) CachingIterator::offsetSet — The offsetSet purpose ### Description ``` public CachingIterator::offsetSet(string $key, mixed $value): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `key` The index of the element to be set. `value` The new value for the `key`. ### Return Values No value is returned. php Yaf_Config_Ini::toArray Yaf\_Config\_Ini::toArray ========================= (Yaf >=1.0.0) Yaf\_Config\_Ini::toArray — Return config as a PHP array ### Description ``` public Yaf_Config_Ini::toArray(): array ``` Returns a PHP array from the [Yaf\_Config\_Ini](class.yaf-config-ini) ### Parameters This function has no parameters. ### Return Values php Yaf_Dispatcher::initView Yaf\_Dispatcher::initView ========================= (Yaf >=1.0.0) Yaf\_Dispatcher::initView — Initialize view and return it ### Description ``` public Yaf_Dispatcher::initView(string $templates_dir, array $options = ?): Yaf_View_Interface ``` ### Parameters `templates_dir` `options` ### Return Values php EvSignal::set EvSignal::set ============= (PECL ev >= 0.2.0) EvSignal::set — Configures the watcher ### Description ``` public EvSignal::set( int $signum ): void ``` Configures the watcher. ### Parameters `signum` Signal number. The same as for [EvSignal::\_\_construct()](evsignal.construct) ### Return Values No value is returned. php pos pos === (PHP 4, PHP 5, PHP 7, PHP 8) pos — Alias of [current()](function.current) ### Description This function is an alias of: [current()](function.current) php eio_readahead eio\_readahead ============== (PECL eio >= 0.0.1dev) eio\_readahead — Perform file readahead into page cache ### Description ``` eio_readahead( mixed $fd, int $offset, int $length, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_readahead()** populates the page cache with data from a file so that subsequent reads from that file will not block on disk I/O. See `READAHEAD(2)` man page for details. ### Parameters `fd` Stream, Socket resource, or numeric file descriptor `offset` Starting point from which data is to be read. `length` Number of bytes to be read. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_readahead()** returns request resource on success, or **`false`** on failure. php ReflectionClass::isIterateable ReflectionClass::isIterateable ============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::isIterateable — Alias of [ReflectionClass::isIterable()](reflectionclass.isiterable) ### Description Alias of [ReflectionClass::isIterable()](reflectionclass.isiterable) As of PHP 7.2.0, instead of the missspelled **RefectionClass::isIterateable()**, [ReflectionClass::isIterable()](reflectionclass.isiterable) should be preferred. php SplFileObject::setFlags SplFileObject::setFlags ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::setFlags — Sets flags for the SplFileObject ### Description ``` public SplFileObject::setFlags(int $flags): void ``` Sets the flags to be used by the [SplFileObject](class.splfileobject). ### Parameters `flags` Bit mask of the flags to set. See [SplFileObject constants](class.splfileobject#splfileobject.constants) for the available flags. ### Return Values No value is returned. ### Examples **Example #1 **SplFileObject::setFlags()** example** ``` <?php $file = new SplFileObject("data.csv"); $file->setFlags(SplFileObject::READ_CSV); foreach ($file as $fields) {     var_dump($fields); } ?> ``` ### See Also * [SplFileObject::getFlags()](splfileobject.getflags) - Gets flags for the SplFileObject php ResourceBundle::count ResourceBundle::count ===================== resourcebundle\_count ===================== (PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0) ResourceBundle::count -- resourcebundle\_count — Get number of elements in the bundle ### Description Object-oriented style ``` public ResourceBundle::count(): int ``` Procedural style ``` resourcebundle_count(ResourceBundle $bundle): int ``` Get the number of elements in the bundle. ### Parameters `bundle` [ResourceBundle](class.resourcebundle) object. ### Return Values Returns number of elements in the bundle. ### Examples **Example #1 **resourcebundle\_count()** example** ``` <?php $r = resourcebundle_create( 'es', "/usr/share/data/myapp"); echo resourcebundle_count($r); ?> ``` **Example #2 OO example** ``` <?php $r = new ResourceBundle( 'es', "/usr/share/data/myapp"); echo $r->count(); ?> ``` The above example will output: ``` 42 ``` ### See Also * [resourcebundle\_get()](resourcebundle.get) - Get data from the bundle php DOMNamedNodeMap::getNamedItem DOMNamedNodeMap::getNamedItem ============================= (PHP 5, PHP 7, PHP 8) DOMNamedNodeMap::getNamedItem — Retrieves a node specified by name ### Description ``` public DOMNamedNodeMap::getNamedItem(string $qualifiedName): ?DOMNode ``` Retrieves a node specified by its `nodeName`. ### Parameters `qualifiedName` The `nodeName` of the node to retrieve. ### Return Values A node (of any type) with the specified `nodeName`, or **`null`** if no node is found. ### See Also * [DOMNamedNodeMap::getNamedItemNS()](domnamednodemap.getnameditemns) - Retrieves a node specified by local name and namespace URI php gzclose gzclose ======= (PHP 4, PHP 5, PHP 7, PHP 8) gzclose — Close an open gz-file pointer ### Description ``` gzclose(resource $stream): bool ``` Closes the given gz-file pointer. ### Parameters `stream` The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **gzclose()** example** ``` <?php $gz = gzopen('somefile.gz','w9'); gzputs ($gz, 'I was added to somefile.gz'); gzclose($gz); ?> ``` ### See Also * [gzopen()](function.gzopen) - Open gz-file php svn_fs_youngest_rev svn\_fs\_youngest\_rev ====================== (PECL svn >= 0.1.0) svn\_fs\_youngest\_rev — Returns the number of the youngest revision in the filesystem ### Description ``` svn_fs_youngest_rev(resource $fs): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the number of the youngest revision in the filesystem ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php ZipArchive::getArchiveComment ZipArchive::getArchiveComment ============================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::getArchiveComment — Returns the Zip archive comment ### Description ``` public ZipArchive::getArchiveComment(int $flags = 0): string|false ``` Returns the Zip archive comment. ### Parameters `flags` If flags is set to **`ZipArchive::FL_UNCHANGED`**, the original unchanged comment is returned. ### Return Values Returns the Zip archive comment or **`false`** on failure. ### Examples **Example #1 Dump an archive comment** ``` <?php $zip = new ZipArchive; $res = $zip->open('test_with_comment.zip'); if ($res === TRUE) {     var_dump($zip->getArchiveComment());     /* Or using the archive property */     var_dump($zip->comment); } else {     echo 'failed, code:' . $res; } ?> ``` php DOMDocumentFragment::__construct DOMDocumentFragment::\_\_construct ================================== (PHP 5, PHP 7, PHP 8) DOMDocumentFragment::\_\_construct — Constructs a [DOMDocumentFragment](class.domdocumentfragment) object ### Description public **DOMDocumentFragment::\_\_construct**() ### Parameters This function has no parameters. php pg_field_name pg\_field\_name =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_field\_name — Returns the name of a field ### Description ``` pg_field_name(PgSql\Result $result, int $field): string ``` **pg\_field\_name()** returns the name of the field occupying the given `field` in the given `result` instance. Field numbering starts from 0. > > **Note**: > > > This function used to be called **pg\_fieldname()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `field` Field number, starting from 0. ### Return Values The field name. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting information about fields** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   $res = pg_query($dbconn, "select * from authors where author = 'Orwell'");   $i = pg_num_fields($res);   for ($j = 0; $j < $i; $j++) {       echo "column $j\n";       $fieldname = pg_field_name($res, $j);       echo "fieldname: $fieldname\n";       echo "printed length: " . pg_field_prtlen($res, $fieldname) . " characters\n";       echo "storage length: " . pg_field_size($res, $j) . " bytes\n";       echo "field type: " . pg_field_type($res, $j) . " \n\n";   } ?> ``` The above example will output: ``` column 0 fieldname: author printed length: 6 characters storage length: -1 bytes field type: varchar column 1 fieldname: year printed length: 4 characters storage length: 2 bytes field type: int2 column 2 fieldname: title printed length: 24 characters storage length: -1 bytes field type: varchar ``` ### See Also * [pg\_field\_num()](function.pg-field-num) - Returns the field number of the named field php SolrDocument::offsetGet SolrDocument::offsetGet ======================= (PECL solr >= 0.9.2) SolrDocument::offsetGet — Retrieves a field ### Description ``` public SolrDocument::offsetGet(string $fieldName): SolrDocumentField ``` This is used to retrieve the field when the object is treated as an array. ### Parameters `fieldName` The name of the field. ### Return Values Returns a SolrDocumentField object. php Gmagick::current Gmagick::current ================ (PECL gmagick >= Unknown) Gmagick::current — The current purpose ### Description ``` public Gmagick::current(): Gmagick ``` Returns reference to the current gmagick object with image pointer at the correct sequence. ### Parameters This function has no parameters. ### Return Values Returns self on success. ### Errors/Exceptions Throws an **GmagickException** on error. php money_format money\_format ============= (PHP 4 >= 4.3.0, PHP 5, PHP 7) money\_format — Formats a number as a currency string **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` money_format(string $format, float $number): string ``` **money\_format()** returns a formatted version of `number`. This function wraps the C library function **strfmon()**, with the difference that this implementation converts only one number at a time. ### Parameters `format` The format specification consists of the following sequence: * a `%` character * optional flags * optional field width * optional left precision * optional right precision * a required conversion character ##### Flags One or more of the optional flags below can be used: `=`f The character `=` followed by a (single byte) character f to be used as the numeric fill character. The default fill character is space. `^` Disable the use of grouping characters (as defined by the current locale). `+` or `(` Specify the formatting style for positive and negative numbers. If `+` is used, the locale's equivalent for `+` and `-` will be used. If `(` is used, negative amounts are enclosed in parenthesis. If no specification is given, the default is `+`. `!` Suppress the currency symbol from the output string. `-` If present, it will make all fields left-justified (padded to the right), as opposed to the default which is for the fields to be right-justified (padded to the left). ##### Field width w A decimal digit string specifying a minimum field width. Field will be right-justified unless the flag `-` is used. Default value is 0 (zero). ##### Left precision `#`n The maximum number of digits (n) expected to the left of the decimal character (e.g. the decimal point). It is used usually to keep formatted output aligned in the same columns, using the fill character if the number of digits is less than n. If the number of actual digits is bigger than n, then this specification is ignored. If grouping has not been suppressed using the `^` flag, grouping separators will be inserted before the fill characters (if any) are added. Grouping separators will not be applied to fill characters, even if the fill character is a digit. To ensure alignment, any characters appearing before or after the number in the formatted output such as currency or sign symbols are padded as necessary with space characters to make their positive and negative formats an equal length. ##### Right precision `.`p A period followed by the number of digits (p) after the decimal character. If the value of p is 0 (zero), the decimal character and the digits to its right will be omitted. If no right precision is included, the default will dictated by the current locale in use. The amount being formatted is rounded to the specified number of digits prior to formatting. ##### Conversion characters `i` The number is formatted according to the locale's international currency format (e.g. for the USA locale: USD 1,234.56). `n` The number is formatted according to the locale's national currency format (e.g. for the de\_DE locale: EU1.234,56). `%` Returns the `%` character. `number` The number to be formatted. ### Return Values Returns the formatted string. Characters before and after the formatting string will be returned unchanged. Non-numeric `number` causes returning **`null`** and emitting **`E_WARNING`**. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | This function has been deprecated. Instead, use [NumberFormatter::formatCurrency()](numberformatter.formatcurrency). | ### Examples **Example #1 **money\_format()** Example** We will use different locales and format specifications to illustrate the use of this function. ``` <?php $number = 1234.56; // let's print the international format for the en_US locale setlocale(LC_MONETARY, 'en_US'); echo money_format('%i', $number) . "\n"; // USD 1,234.56 // Italian national format with 2 decimals` setlocale(LC_MONETARY, 'it_IT'); echo money_format('%.2n', $number) . "\n"; // Eu 1.234,56 // Using a negative number $number = -1234.5672; // US national format, using () for negative numbers // and 10 digits for left precision setlocale(LC_MONETARY, 'en_US'); echo money_format('%(#10n', $number) . "\n"; // ($        1,234.57) // Similar format as above, adding the use of 2 digits of right // precision and '*' as a fill character echo money_format('%=*(#10.2n', $number) . "\n"; // ($********1,234.57) // Let's justify to the left, with 14 positions of width, 8 digits of // left precision, 2 of right precision, without the grouping character // and using the international format for the de_DE locale. setlocale(LC_MONETARY, 'de_DE'); echo money_format('%=*^-14#8.2i', 1234.56) . "\n"; // Eu 1234,56**** // Let's add some blurb before and after the conversion specification setlocale(LC_MONETARY, 'en_GB'); $fmt = 'The final value is %i (after a 10%% discount)'; echo money_format($fmt, 1234.56) . "\n"; // The final value is  GBP 1,234.56 (after a 10% discount) ?> ``` ### Notes > > **Note**: > > > The function **money\_format()** is only defined if the system has strfmon capabilities. For example, Windows does not, so **money\_format()** is undefined in Windows. > > > > **Note**: > > > The **`LC_MONETARY`** category of the locale settings, affects the behavior of this function. Use [setlocale()](function.setlocale) to set to the appropriate default locale before using this function. > > ### See Also * [setlocale()](function.setlocale) - Set locale information * [sscanf()](function.sscanf) - Parses input from a string according to a format * [sprintf()](function.sprintf) - Return a formatted string * [printf()](function.printf) - Output a formatted string * [number\_format()](function.number-format) - Format a number with grouped thousands php fbird_connect fbird\_connect ============== (PHP 5, PHP 7 < 7.4.0) fbird\_connect — Alias of [ibase\_connect()](function.ibase-connect) ### Description This function is an alias of: [ibase\_connect()](function.ibase-connect). ### See Also * [fbird\_pconnect()](function.fbird-pconnect) - Alias of ibase\_pconnect * [fbird\_close()](function.fbird-close) - Alias of ibase\_close php IntlCalendar::isWeekend IntlCalendar::isWeekend ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::isWeekend — Whether a certain date/time is in the weekend ### Description Object-oriented style ``` public IntlCalendar::isWeekend(?float $timestamp = null): bool ``` Procedural style ``` intlcal_is_weekend(IntlCalendar $calendar, ?float $timestamp = null): bool ``` Returns whether either the obejctʼs current time or the provided timestamp occur during a weekend in this objectʼs calendar system. This function requires ICU 4.4 or later. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `timestamp` An optional timestamp representing the number of milliseconds since the epoch, excluding leap seconds. If **`null`**, this objectʼs current time is used instead. ### Return Values A bool indicating whether the given or this objectʼs time occurs in a weekend. On failure **`false`** is also returned. To detect error conditions use [intl\_get\_error\_code()](function.intl-get-error-code), or set up Intl to throw [exceptions](https://www.php.net/manual/en/intl.configuration.php#ini.intl.use-exceptions). ### Examples **Example #1 **IntlCalendar::isWeekend()**** ``` <?php ini_set('date.timezone', 'Europe/Lisbon'); $cal = new IntlGregorianCalendar(NULL, 'en_US'); $cal->set(2013, 6 /* July */, 7); // a Sunday  var_dump($cal->isWeekend()); // true var_dump($cal->isWeekend(strtotime('2013-07-01 00:00:00'))); // false, Monday $cal = new IntlGregorianCalendar(NULL, 'ar_SA'); $cal->set(2013, 6 /* July */, 7); // a Sunday  var_dump($cal->isWeekend()); // false, Sunday not in weekend in this calendar ``` ### See Also * [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) - Tell whether a day is a weekday, weekend or a day that has a transition between the two * [IntlCalendar::getWeekendTransition()](intlcalendar.getweekendtransition) - Get time of the day at which weekend begins or ends
programming_docs
php preg_match preg\_match =========== (PHP 4, PHP 5, PHP 7, PHP 8) preg\_match — Perform a regular expression match ### Description ``` preg_match( string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0 ): int|false ``` Searches `subject` for a match to the regular expression given in `pattern`. ### Parameters `pattern` The pattern to search for, as a string. `subject` The input string. `matches` If `matches` is provided, then it is filled with the results of search. $matches[0] will contain the text that matched the full pattern, $matches[1] will have the text that matched the first captured parenthesized subpattern, and so on. `flags` `flags` can be a combination of the following flags: **`PREG_OFFSET_CAPTURE`** If this flag is passed, for every occurring match the appendant string offset (in bytes) will also be returned. Note that this changes the value of `matches` into an array where every element is an array consisting of the matched string at offset `0` and its string offset into `subject` at offset `1`. ``` <?php preg_match('/(foo)(bar)(baz)/', 'foobarbaz', $matches, PREG_OFFSET_CAPTURE); print_r($matches); ?> ``` The above example will output: ``` Array ( [0] => Array ( [0] => foobarbaz [1] => 0 ) [1] => Array ( [0] => foo [1] => 0 ) [2] => Array ( [0] => bar [1] => 3 ) [3] => Array ( [0] => baz [1] => 6 ) ) ``` **`PREG_UNMATCHED_AS_NULL`** If this flag is passed, unmatched subpatterns are reported as **`null`**; otherwise they are reported as an empty string. ``` <?php preg_match('/(a)(b)*(c)/', 'ac', $matches); var_dump($matches); preg_match('/(a)(b)*(c)/', 'ac', $matches, PREG_UNMATCHED_AS_NULL); var_dump($matches); ?> ``` The above example will output: ``` array(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> string(0) "" [3]=> string(1) "c" } array(4) { [0]=> string(2) "ac" [1]=> string(1) "a" [2]=> NULL [3]=> string(1) "c" } ``` `offset` Normally, the search starts from the beginning of the subject string. The optional parameter `offset` can be used to specify the alternate place from which to start the search (in bytes). > > **Note**: > > > Using `offset` is not equivalent to passing `substr($subject, $offset)` to **preg\_match()** in place of the subject string, because `pattern` can contain assertions such as *^*, *$* or *(?<=x)*. Compare: > > > > ``` > <?php > $subject = "abcdef"; > $pattern = '/^def/'; > preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3); > print_r($matches); > ?> > ``` > The above example will output: > > > ``` > > Array > ( > ) > > ``` > while this example > > > ``` > <?php > $subject = "abcdef"; > $pattern = '/^def/'; > preg_match($pattern, substr($subject,3), $matches, PREG_OFFSET_CAPTURE); > print_r($matches); > ?> > ``` > will produce > > > ``` > > Array > ( > [0] => Array > ( > [0] => def > [1] => 0 > ) > > ) > > ``` > Alternatively, to avoid using [substr()](function.substr), use the `\G` assertion rather than the `^` anchor, or the `A` modifier instead, both of which work with the `offset` parameter. > > ### Return Values **preg\_match()** returns 1 if the `pattern` matches given `subject`, 0 if it does not, or **`false`** on failure. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Errors/Exceptions If the regex pattern passed does not compile to a valid regex, an **`E_WARNING`** is emitted. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | The **`PREG_UNMATCHED_AS_NULL`** is now supported for the `$flags` parameter. | ### Examples **Example #1 Find the string of text "php"** ``` <?php // The "i" after the pattern delimiter indicates a case-insensitive search if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {     echo "A match was found."; } else {     echo "A match was not found."; } ?> ``` **Example #2 Find the word "web"** ``` <?php /* The \b in the pattern indicates a word boundary, so only the distinct  * word "web" is matched, and not a word partial like "webbing" or "cobweb" */ if (preg_match("/\bweb\b/i", "PHP is the web scripting language of choice.")) {     echo "A match was found."; } else {     echo "A match was not found."; } if (preg_match("/\bweb\b/i", "PHP is the website scripting language of choice.")) {     echo "A match was found."; } else {     echo "A match was not found."; } ?> ``` **Example #3 Getting the domain name out of a URL** ``` <?php // get host name from URL preg_match('@^(?:http://)?([^/]+)@i',     "http://www.php.net/index.html", $matches); $host = $matches[1]; // get last two segments of host name preg_match('/[^.]+\.[^.]+$/', $host, $matches); echo "domain name is: {$matches[0]}\n"; ?> ``` The above example will output: ``` domain name is: php.net ``` **Example #4 Using named subpattern** ``` <?php $str = 'foobar: 2008'; preg_match('/(?P<name>\w+): (?P<digit>\d+)/', $str, $matches); /* Alternative */ // preg_match('/(?<name>\w+): (?<digit>\d+)/', $str, $matches); print_r($matches); ?> ``` The above example will output: ``` Array ( [0] => foobar: 2008 [name] => foobar [1] => foobar [digit] => 2008 [2] => 2008 ) ``` ### Notes **Tip** Do not use **preg\_match()** if you only want to check if one string is contained in another string. Use [strpos()](function.strpos) instead as it will be faster. ### See Also * [PCRE Patterns](https://www.php.net/manual/en/pcre.pattern.php) * [preg\_quote()](function.preg-quote) - Quote regular expression characters * [preg\_match\_all()](function.preg-match-all) - Perform a global regular expression match * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace * [preg\_split()](function.preg-split) - Split string by a regular expression * [preg\_last\_error()](function.preg-last-error) - Returns the error code of the last PCRE regex execution * [preg\_last\_error\_msg()](function.preg-last-error-msg) - Returns the error message of the last PCRE regex execution php phpdbg_start_oplog phpdbg\_start\_oplog ==================== (PHP 7, PHP 8) phpdbg\_start\_oplog — ### Description ``` phpdbg_start_oplog(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php array_product array\_product ============== (PHP 5 >= 5.1.0, PHP 7, PHP 8) array\_product — Calculate the product of values in an array ### Description ``` array_product(array $array): int|float ``` **array\_product()** returns the product of values in an array. ### Parameters `array` The array. ### Return Values Returns the product as an integer or float. ### Examples **Example #1 **array\_product()** examples** ``` <?php $a = array(2, 4, 6, 8); echo "product(a) = " . array_product($a) . "\n"; echo "product(array()) = " . array_product(array()) . "\n"; ?> ``` The above example will output: ``` product(a) = 384 product(array()) = 1 ``` php imageavif imageavif ========= (PHP 8 >= 8.1.0) imageavif — Output image to browser or file ### Description ``` imageavif( GdImage $image, resource|string|null $file = null, int $quality = -1, int $speed = -1 ): bool ``` Outputs or saves a AVIF Raster image from the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `file` The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly. `quality` `quality` is optional, and ranges from 0 (worst quality, smaller file) to 100 (best quality, larger file). If `-1` is provided, the default value `30` is used. `speed` `speed` is optional, and ranges from 0 (slow, smaller file) to 10 (fast, larger file). If `-1` is provided, the default value `6` is used. ### Return Values Returns **`true`** on success or **`false`** on failure. **Caution**However, if libgd fails to output the image, this function returns **`true`**. ### See Also * [imagepng()](function.imagepng) - Output a PNG image to either the browser or a file * [imagewbmp()](function.imagewbmp) - Output image to browser or file * [imagejpeg()](function.imagejpeg) - Output image to browser or file * [imagetypes()](function.imagetypes) - Return the image types supported by this PHP build php get_resource_id get\_resource\_id ================= (PHP 8) get\_resource\_id — Returns an integer identifier for the given resource ### Description ``` get_resource_id(resource $resource): int ``` This function provides a type-safe way for generating the integer identifier for a resource. ### Parameters `resource` The evaluated resource handle. ### Return Values The int identifier for the given `resource`. This function is essentially an int cast of `resource` to make it easier to retrieve the resource ID. ### Examples **Example #1 **get\_resource\_id()** produces the same result as an int cast** ``` <?php $handle = fopen("php://stdout", "w"); echo (int) $handle . "\n"; echo get_resource_id($handle); ?> ``` The above example will output something similar to: ``` 698 698 ``` ### See Also * [get\_resource\_type()](function.get-resource-type) - Returns the resource type php ReflectionProperty::setAccessible ReflectionProperty::setAccessible ================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionProperty::setAccessible — Set property accessibility ### Description ``` public ReflectionProperty::setAccessible(bool $accessible): void ``` Enables access to a protected or private property via the [ReflectionProperty::getValue()](reflectionproperty.getvalue) and [ReflectionProperty::setValue()](reflectionproperty.setvalue) methods. > **Note**: As of PHP 8.1.0, calling this method has no effect; all properties are accessible by default. > > ### Parameters `accessible` **`true`** to allow accessibility, or **`false`**. ### Return Values No value is returned. ### Examples **Example #1 Simple Class definition** ``` <?php class MyClass {     private $foo = 'bar'; } $property = new ReflectionProperty("MyClass", "foo"); $property->setAccessible(true); $obj = new MyClass(); echo $property->getValue($obj); echo $obj->foo; ?> ``` The above example will output something similar to: ``` bar Fatal error: Uncaught Error: Cannot access private property MyClass::$foo in /in/WJqTv:12 ``` ### See Also * [ReflectionProperty::isPrivate()](reflectionproperty.isprivate) - Checks if property is private * [ReflectionProperty::isProtected()](reflectionproperty.isprotected) - Checks if property is protected php QuickHashIntHash::saveToString QuickHashIntHash::saveToString ============================== (PECL quickhash >= Unknown) QuickHashIntHash::saveToString — This method returns a serialized version of the hash ### Description ``` public QuickHashIntHash::saveToString(): string ``` This method returns a serialized version of the hash in the same format that [QuickHashIntHash::loadFromString()](quickhashinthash.loadfromstring) can read. ### Parameters This function has no parameters. ### Return Values This method returns a string containing a serialized format of the hash. Each element is stored as a four byte value in the Endianness that the current system uses. ### Examples **Example #1 **QuickHashIntHash::saveToString()** example** ``` <?php $hash = new QuickHashIntHash( 1024 ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->add( 4, 34 ) ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->add( 4, 55 ) ); var_dump( $hash->saveToString() ); ?> ``` php GearmanClient::setCreatedCallback GearmanClient::setCreatedCallback ================================= (PECL gearman >= 0.5.0) GearmanClient::setCreatedCallback — Set a callback for when a task is queued ### Description ``` public GearmanClient::setCreatedCallback(string $callback): bool ``` Sets a function to be called when a task is received and queued by the Gearman job server. The callback should accept a single argument, a [GearmanTask](class.gearmantask) object. ### Parameters `callback` A function to call ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task * [GearmanClient::setCompleteCallback()](gearmanclient.setcompletecallback) - Set a function to be called on task completion * [GearmanClient::setExceptionCallback()](gearmanclient.setexceptioncallback) - Set a callback for worker exceptions * [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure * [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status * [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings * [GearmanClient::setWorkloadCallback()](gearmanclient.setworkloadcallback) - Set a callback for accepting incremental data updates php ArrayObject::append ArrayObject::append =================== (PHP 5, PHP 7, PHP 8) ArrayObject::append — Appends the value ### Description ``` public ArrayObject::append(mixed $value): void ``` Appends a new value as the last element. > > **Note**: > > > This method cannot be called when the [ArrayObject](class.arrayobject) was constructed from an object. Use [ArrayObject::offsetSet()](arrayobject.offsetset) instead. > > ### Parameters `value` The value being appended. ### Return Values No value is returned. ### Examples **Example #1 **ArrayObject::append()** example** ``` <?php $arrayobj = new ArrayObject(array('first','second','third')); $arrayobj->append('fourth'); $arrayobj->append(array('five', 'six')); var_dump($arrayobj); ?> ``` The above example will output: ``` object(ArrayObject)#1 (5) { [0]=> string(5) "first" [1]=> string(6) "second" [2]=> string(5) "third" [3]=> string(6) "fourth" [4]=> array(2) { [0]=> string(4) "five" [1]=> string(3) "six" } } ``` ### See Also * [ArrayObject::offsetSet()](arrayobject.offsetset) - Sets the value at the specified index to newval php get_debug_type get\_debug\_type ================ (PHP 8) get\_debug\_type — Gets the type name of a variable in a way that is suitable for debugging ### Description ``` get_debug_type(mixed $value): string ``` Returns the resolved name of the PHP variable `value`. This function will resolve objects to their class name, resources to their resource type name, and scalar values to their common name as would be used in type declarations. This function differs from [gettype()](function.gettype) in that it returns type names that are more consistent with actual usage, rather than those present for historical reasons. ### Parameters `value` The variable being type checked. ### Return Values Possible values for the returned string are: | Type + State | Return Value | Notes | | --- | --- | --- | | null | `"null"` | - | | Booleans (true or false) | `"bool"` | - | | Integers | `"int"` | - | | Floats | `"float"` | - | | Strings | `"string"` | - | | Arrays | `"array"` | - | | Resources | `"resource (resourcename)"` | - | | Resources (Closed) | `"resource (closed)"` | Example: A file stream after being closed with fclose. | | Objects from Named Classes | The full name of the class including its namespace e.g. `Foo\Bar` | - | | Objects from Anonymous Classes | `"class@anonymous"` | Anonymous classes are those created through the $x = new class { ... } syntax | ### Examples **Example #1 **get\_debug\_type()** example** ``` <?php echo get_debug_type(null) . PHP_EOL; echo get_debug_type(true) . PHP_EOL; echo get_debug_type(1) . PHP_EOL; echo get_debug_type(0.1) . PHP_EOL; echo get_debug_type("foo") . PHP_EOL; echo get_debug_type([]) . PHP_EOL; $fp = fopen(__FILE__, 'rb'); echo get_debug_type($fp) . PHP_EOL; fclose($fp); echo get_debug_type($fp) . PHP_EOL; echo get_debug_type(new stdClass) . PHP_EOL; echo get_debug_type(new class {}) . PHP_EOL; ?> ``` The above example will output something similar to: ``` null bool int float string array resource (stream) resource (closed) stdClass class@anonymous ``` ### See Also * [gettype()](function.gettype) - Get the type of a variable * [get\_class()](function.get-class) - Returns the name of the class of an object php sodium_crypto_stream sodium\_crypto\_stream ====================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_stream — Generate a deterministic sequence of bytes from a seed ### Description ``` sodium_crypto_stream(int $length, string $nonce, string $key): string ``` Generate a deterministic sequence of bytes from a seed, using the XSalsa20 stream cipher. ### Parameters `length` The number of bytes to return. `nonce` A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php)). `key` Encryption key (256-bit). ### Return Values String of pseudorandom bytes. php snmp_set_oid_output_format snmp\_set\_oid\_output\_format ============================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) snmp\_set\_oid\_output\_format — Set the OID output format ### Description ``` snmp_set_oid_output_format(int $format): bool ``` **snmp\_set\_oid\_output\_format()** sets the output format to be full or numeric. ### Parameters `format` **OID .1.3.6.1.2.1.1.3.0 representation for various `format` values**| **`SNMP_OID_OUTPUT_FULL`** | .iso.org.dod.internet.mgmt.mib-2.system.sysUpTime.sysUpTimeInstance | | **`SNMP_OID_OUTPUT_NUMERIC`** | .1.3.6.1.2.1.1.3.0 | | **`SNMP_OID_OUTPUT_MODULE`** | DISMAN-EVENT-MIB::sysUpTimeInstance | | **`SNMP_OID_OUTPUT_SUFFIX`** | sysUpTimeInstance | | **`SNMP_OID_OUTPUT_UCD`** | system.sysUpTime.sysUpTimeInstance | | **`SNMP_OID_OUTPUT_NONE`** | Undefined | ### Return Values Always returns **`true`**. ### Examples **Example #1 Using [snmprealwalk()](function.snmprealwalk)** ``` <?php  snmp_read_mib("/usr/share/mibs/netsnmp/NET-SNMP-TC");  // default or SNMP_OID_OUTPUT_MODULE  print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );  snmp_set_oid_output_format(SNMP_OID_OUTPUT_NUMERIC);  print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') );  snmp_set_oid_output_format(SNMP_OID_OUTPUT_FULL);  print_r( snmprealwalk('localhost', 'public', 'RFC1213-MIB::sysObjectID') ); ?> ``` The above would output: ``` Array ( [RFC1213-MIB::sysObjectID.0] => OID: NET-SNMP-TC::linux ) Array ( [.1.3.6.1.2.1.1.2.0] => OID: .1.3.6.1.4.1.8072.3.2.10 ) Array ( [.iso.org.dod.internet.mgmt.mib-2.system.sysObjectID.0] => OID: .iso.org.dod.internet.private.enterprises.netSnmp.netSnmpEnumerations.netSnmpAgentOIDs.linux ) ```
programming_docs
php Imagick::paintOpaqueImage Imagick::paintOpaqueImage ========================= (PECL imagick 2, PECL imagick 3) Imagick::paintOpaqueImage — Change any pixel that matches color **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::paintOpaqueImage( mixed $target, mixed $fill, float $fuzz, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` Changes any pixel that matches color with the color defined by fill. ### Parameters `target` Change this target color to the fill color within the image. An ImagickPixel object or a string representing the target color. `fill` An ImagickPixel object or a string representing the fill color. `fuzz` The fuzz member of image defines how much tolerance is acceptable to consider two colors as the same. `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel). ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as first and second parameter. Previous versions allow only an ImagickPixel object. | php SolrDocument::getChildDocumentsCount SolrDocument::getChildDocumentsCount ==================================== (PECL solr >= 2.3.0) SolrDocument::getChildDocumentsCount — Returns the number of child documents ### Description ``` public SolrDocument::getChildDocumentsCount(): int ``` Returns the number of child documents ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrDocument::hasChildDocuments()](solrdocument.haschilddocuments) - Checks whether the document has any child documents * [SolrDocument::getChildDocuments()](solrdocument.getchilddocuments) - Returns an array of child documents (SolrDocument) php XMLReader::moveToNextAttribute XMLReader::moveToNextAttribute ============================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::moveToNextAttribute — Position cursor on the next Attribute ### Description ``` public XMLReader::moveToNextAttribute(): bool ``` Moves cursor to the next Attribute if positioned on an Attribute or moves to first attribute if positioned on an Element. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute * [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute * [XMLReader::moveToAttributeNo()](xmlreader.movetoattributeno) - Move cursor to an attribute by index * [XMLReader::moveToAttributeNs()](xmlreader.movetoattributens) - Move cursor to a named attribute * [XMLReader::moveToFirstAttribute()](xmlreader.movetofirstattribute) - Position cursor on the first Attribute php Parle pattern matching Parle pattern matching ====================== Table of Contents ----------------- * [Character representations](https://www.php.net/manual/en/parle.regex.chars.php) * [Character classes](https://www.php.net/manual/en/parle.regex.charclass.php) * [Unicode character classes](https://www.php.net/manual/en/parle.regex.unicodecharclass.php) * [Alternation and repetition](https://www.php.net/manual/en/parle.regex.alternation.php) * [Anchors](https://www.php.net/manual/en/parle.regex.anchors.php) * [Grouping](https://www.php.net/manual/en/parle.regex.grouping.php) Parle supports regex matching similar to flex. Also supported are the following POSIX character sets: `[:alnum:]`, `[:alpha:]`, `[:blank:]`, `[:cntrl:]`, `[:digit:]`, `[:graph:]`, `[:lower:]`, `[:print:]`, `[:punct:]`, `[:space:]`, `[:upper:]` and `[:xdigit:]`. The Unicode character classes are currently not enabled by default, pass --enable-parle-utf32 to make them available. A particular encoding can be mapped with a correctly constructed regex. For example, to match the EURO symbol encoded in UTF-8, the regular expression `[\xe2][\x82][\xac]` can be used. The pattern for an UTF-8 encoded string could be `[ -\x7f]{+}[\x80-\xbf]{+}[\xc2-\xdf]{+}[\xe0-\xef]{+}[\xf0-\xff]+`. php IntlCalendar::clear IntlCalendar::clear =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::clear — Clear a field or all fields ### Description Object-oriented style ``` public IntlCalendar::clear(?int $field = null): bool ``` Procedural style ``` intlcal_clear(IntlCalendar $calendar, ?int $field = null): bool ``` Clears either all of the fields or a specific field. A cleared field is marked as unset, giving it the lowest priority against overlapping fields or even default values when calculating the time. Additionally, its value is set to `0`, though given the fieldʼs low priority, its value may have been internally set to another value by the time the field has finished been queried. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values Always returns **`true`**. ### Examples **Example #1 **IntlCalendar::clear()** examples** ``` <?php ini_set('intl.default_locale', 'es_ES'); ini_set('date.timezone', 'UTC'); $fields = array(     'FIELD_ERA'                  => 0,     'FIELD_YEAR'                 => 1,     'FIELD_MONTH'                => 2,     'FIELD_WEEK_OF_YEAR'         => 3,     'FIELD_WEEK_OF_MONTH'        => 4,     'FIELD_DATE'                 => 5,     'FIELD_DAY_OF_YEAR'          => 6,     'FIELD_DAY_OF_WEEK'          => 7,     'FIELD_DAY_OF_WEEK_IN_MONTH' => 8,     'FIELD_AM_PM'                => 9,     'FIELD_HOUR'                 => 10,     'FIELD_HOUR_OF_DAY'          => 11,     'FIELD_MINUTE'               => 12,     'FIELD_SECOND'               => 13,     'FIELD_MILLISECOND'          => 14,     'FIELD_ZONE_OFFSET'          => 15,     'FIELD_DST_OFFSET'           => 16,     'FIELD_YEAR_WOY'             => 17,     'FIELD_DOW_LOCAL'            => 18,     'FIELD_EXTENDED_YEAR'        => 19,     'FIELD_JULIAN_DAY'           => 20,     'FIELD_MILLISECONDS_IN_DAY'  => 21,     'FIELD_IS_LEAP_MONTH'        => 22,     'FIELD_FIELD_COUNT'          => 23, ); function getSetFields(IntlCalendar $cal) {     global $fields;     $ret = array();     foreach ($fields as $name => $value) {         if ($cal->isSet($value)) {             $ret[] = $name;         }     }     return $ret; } $cal = new IntlGregorianCalendar(2013, 2 /* March */, 15); echo "After GregorianCalendar creation\n"; print_r(getSetFields($cal)); echo "\n"; echo IntlDateFormatter::formatObject($cal), "\n"; echo "After the formatter requested the extended year\n"; print_r(getSetFields($cal)); echo "\n"; $cal->clear(IntlCalendar::FIELD_YEAR); echo "After the year has been cleared, the date stays the same\n"; echo IntlDateFormatter::formatObject($cal), "\n"; echo "because FIELD_EXTENDED_YEAR is still set\n"; print_r(getSetFields($cal)); echo "\n"; var_dump($cal->clear(IntlCalendar::FIELD_EXTENDED_YEAR)); echo "After the extended year has been cleared\n"; print_r(getSetFields($cal)); echo IntlDateFormatter::formatObject($cal), "\n"; echo "\n"; echo "After the fields are recalculated,\n"         . " extended year is set again (to 1970)\n"; print_r(getSetFields($cal)); echo "\n"; $cal->clear(); echo "After calling variant with no arguments\n"; print_r(getSetFields($cal)); echo IntlDateFormatter::formatObject($cal), "\n"; ``` The above example will output: ``` After GregorianCalendar creation Array ( [0] => FIELD_ERA [1] => FIELD_YEAR [2] => FIELD_MONTH [3] => FIELD_DATE ) 15/03/2013 00:00:00 After the formatter requested the extended year Array ( [0] => FIELD_ERA [1] => FIELD_YEAR [2] => FIELD_MONTH [3] => FIELD_DATE [4] => FIELD_EXTENDED_YEAR ) After the year has been cleared, the date stays the same 15/03/2013 00:00:00 because FIELD_EXTENDED_YEAR is still set Array ( [0] => FIELD_ERA [1] => FIELD_MONTH [2] => FIELD_DATE [3] => FIELD_EXTENDED_YEAR ) bool(true) After the extended year has been cleared Array ( [0] => FIELD_ERA [1] => FIELD_MONTH [2] => FIELD_DATE ) 15/03/1970 00:00:00 After the fields are recalculated, extended year is set again (to 1970) Array ( [0] => FIELD_ERA [1] => FIELD_MONTH [2] => FIELD_DATE [3] => FIELD_EXTENDED_YEAR ) After calling variant with no arguments Array ( ) 01/01/1970 00:00:00 ``` php snmp3_getnext snmp3\_getnext ============== (PHP 5, PHP 7, PHP 8) snmp3\_getnext — Fetch the SNMP object which follows the given object id ### Description ``` snmp3_getnext( string $hostname, string $security_name, string $security_level, string $auth_protocol, string $auth_passphrase, string $privacy_protocol, string $privacy_passphrase, array|string $object_id, int $timeout = -1, int $retries = -1 ): mixed ``` The **snmp3\_getnext()** function is used to read the value of the SNMP object that follows the specified `object_id`. ### Parameters `hostname` The hostname of the SNMP agent (server). `security_name` the security name, usually some kind of username `security_level` the security level (noAuthNoPriv|authNoPriv|authPriv) `auth_protocol` the authentication protocol (`"MD5"`, `"SHA"`, `"SHA256"`, or `"SHA512"`) `auth_passphrase` the authentication pass phrase `privacy_protocol` the privacy protocol (DES or AES) `privacy_passphrase` the privacy pass phrase `object_id` The SNMP object id. `timeout` The number of microseconds until the first timeout. `retries` The number of times to retry if timeouts occur. ### Return Values Returns SNMP object value on success or **`false`** on error. In case of an error, an E\_WARNING message is shown. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `auth_protocol` now accepts `"SHA256"` and `"SHA512"` when supported by libnetsnmp. | ### Examples **Example #1 Using **snmp3\_getnext()**** ``` <?php $nameOfSecondInterface = snmp3_getnext('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName.1'); ?> ``` ### See Also * [snmp3\_get()](function.snmp3-get) - Fetch an SNMP object * [snmp3\_walk()](function.snmp3-walk) - Fetch all the SNMP objects from an agent php Yaf_Route_Map::__construct Yaf\_Route\_Map::\_\_construct ============================== (Yaf >=1.0.0) Yaf\_Route\_Map::\_\_construct — The \_\_construct purpose ### Description public **Yaf\_Route\_Map::\_\_construct**(string `$controller_prefer` = **`false`**, string `$delimiter` = "") ### Parameters `controller_prefer` Whether the result should considering as controller or action `delimiter` ### Return Values ### Examples **Example #1 **Yaf\_Route\_Map()**example** ``` <?php    /**     * Add a map route to Yaf_Router route stack     */     Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",         new Yaf_Route_Map()); ?> ``` The above example will output something similar to: ``` /* for http://yourdomain.com/product/foo/bar * route will result in following values: */ array( "controller" => "product_foo_bar", ) ``` **Example #2 **Yaf\_Route\_Map()**example** ``` <?php    /**     * Add a map route to Yaf_Router route stack     */     Yaf_Dispatcher::getInstance()->getRouter()->addRoute("name",         new Yaf_Route_Map(true, "_")); ?> ``` The above example will output something similar to: ``` /* for http://yourdomain.com/user/list/_/foo/22 * route will result in following values: */ array( "action" => "user_list", ) /** * and request parameters: */ array( "foo" => 22, ) ``` **Example #3 **Yaf\_Route\_Map()**example** ``` <?php    /**     * Add a map route to Yaf_Router route stack by calling addconfig     */     $config = array(         "name" => array(            "type"  => "map",         //Yaf_Route_Map route            "controllerPrefer" => FALSE,            "delimiter"        => "#!",             ),     );     Yaf_Dispatcher::getInstance()->getRouter()->addConfig(         new Yaf_Config_Simple($config)); ?> ``` ### See Also * [Yaf\_Router::addRoute()](yaf-router.addroute) - Add new Route into Router * [Yaf\_Route\_Static](class.yaf-route-static) * [Yaf\_Route\_Supervar](class.yaf-route-supervar) * [Yaf\_Route\_Simple](class.yaf-route-simple) * [Yaf\_Route\_Regex](class.yaf-route-regex) * [Yaf\_Route\_Rewrite](class.yaf-route-rewrite) php SolrQuery::getGroupOffset SolrQuery::getGroupOffset ========================= (PECL solr >= 2.2.0) SolrQuery::getGroupOffset — Returns the group.offset value ### Description ``` public SolrQuery::getGroupOffset(): int ``` Returns the group.offset value ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter php imap_fetchbody imap\_fetchbody =============== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_fetchbody — Fetch a particular section of the body of the message ### Description ``` imap_fetchbody( IMAP\Connection $imap, int $message_num, string $section, int $flags = 0 ): string|false ``` Fetch of a particular section of the body of the specified messages. Body parts are not decoded by this function. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_num` The message number `section` The part number. It is a string of integers delimited by period which index into a body part list as per the IMAP4 specification `flags` A bitmask with one or more of the following: * **`FT_UID`** - The `message_num` is a UID * **`FT_PEEK`** - Do not set the \Seen flag if not already set * **`FT_INTERNAL`** - The return string is in internal format, will not canonicalize to CRLF. ### Return Values Returns a particular section of the body of the specified messages as a text string, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_savebody()](function.imap-savebody) - Save a specific body section to a file * [imap\_fetchstructure()](function.imap-fetchstructure) - Read the structure of a particular message php ob_get_length ob\_get\_length =============== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) ob\_get\_length — Return the length of the output buffer ### Description ``` ob_get_length(): int|false ``` This will return the length of the contents in the output buffer, in bytes. ### Parameters This function has no parameters. ### Return Values Returns the length of the output buffer contents, in bytes, or **`false`** if no buffering is active. ### Examples **Example #1 A simple **ob\_get\_length()** example** ``` <?php ob_start(); echo "Hello "; $len1 = ob_get_length(); echo "World"; $len2 = ob_get_length(); ob_end_clean(); echo $len1 . ", " . $len2; ?> ``` The above example will output: ``` 6, 11 ``` ### See Also * [ob\_start()](function.ob-start) - Turn on output buffering * [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer php Ds\Set::first Ds\Set::first ============= (PECL ds >= 1.0.0) Ds\Set::first — Returns the first value in the set ### Description ``` public Ds\Set::first(): mixed ``` Returns the first value in the set. ### Parameters This function has no parameters. ### Return Values The first value in the set. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Set::first()** example** ``` <?php $set = new \Ds\Set([1, 2, 3]); var_dump($set->first()); ?> ``` The above example will output something similar to: ``` int(1) ``` php The Yaf_Exception_LoadFailed class The Yaf\_Exception\_LoadFailed class ==================================== Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Exception\_LoadFailed** extends [Yaf\_Exception](class.yaf-exception) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/ ``` public Yaf_Exception::getPrevious(): void ``` } php The tidy class The tidy class ============== Introduction ------------ (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) An HTML node in an HTML file, as detected by tidy. Class synopsis -------------- class **tidy** { /\* Properties \*/ public ?string [$errorBuffer](tidy.props.errorbuffer) = null; public ?string [$value](class.tidy#tidy.props.value) = null; /\* Methods \*/ public [\_\_construct](tidy.construct)( ?string `$filename` = **`null`**, array|string|null `$config` = **`null`**, ?string `$encoding` = **`null`**, bool `$useIncludePath` = **`false`** ) ``` public body(): ?tidyNode ``` ``` public cleanRepair(): bool ``` ``` public diagnose(): bool ``` ``` public getConfig(): array ``` ``` public getHtmlVer(): int ``` ``` public getOpt(string $option): string|int|bool ``` ``` public getOptDoc(string $option): string|false ``` ``` public getRelease(): string ``` ``` public getStatus(): int ``` ``` public head(): ?tidyNode ``` ``` public html(): ?tidyNode ``` ``` public isXhtml(): bool ``` ``` public isXml(): bool ``` ``` public parseFile( string $filename, array|string|null $config = null, ?string $encoding = null, bool $useIncludePath = false ): bool ``` ``` public parseString(string $string, array|string|null $config = null, ?string $encoding = null): bool ``` ``` public static repairFile( string $filename, array|string|null $config = null, ?string $encoding = null, bool $useIncludePath = false ): string|false ``` ``` public static repairString(string $string, array|string|null $config = null, ?string $encoding = null): string|false ``` ``` public root(): ?tidyNode ``` } Properties ---------- value The HTML representation of the node, including the surrounding tags. Table of Contents ----------------- * [tidy::body](tidy.body) — Returns a tidyNode object starting from the <body> tag of the tidy parse tree * [tidy::cleanRepair](tidy.cleanrepair) — Execute configured cleanup and repair operations on parsed markup * [tidy::\_\_construct](tidy.construct) — Constructs a new tidy object * [tidy::diagnose](tidy.diagnose) — Run configured diagnostics on parsed and repaired markup * [tidy::$errorBuffer](tidy.props.errorbuffer) — Return warnings and errors which occurred parsing the specified document * [tidy::getConfig](tidy.getconfig) — Get current Tidy configuration * [tidy::getHtmlVer](tidy.gethtmlver) — Get the Detected HTML version for the specified document * [tidy::getOpt](tidy.getopt) — Returns the value of the specified configuration option for the tidy document * [tidy::getOptDoc](tidy.getoptdoc) — Returns the documentation for the given option name * [tidy::getRelease](tidy.getrelease) — Get release date (version) for Tidy library * [tidy::getStatus](tidy.getstatus) — Get status of specified document * [tidy::head](tidy.head) — Returns a tidyNode object starting from the <head> tag of the tidy parse tree * [tidy::html](tidy.html) — Returns a tidyNode object starting from the <html> tag of the tidy parse tree * [tidy::isXhtml](tidy.isxhtml) — Indicates if the document is a XHTML document * [tidy::isXml](tidy.isxml) — Indicates if the document is a generic (non HTML/XHTML) XML document * [tidy::parseFile](tidy.parsefile) — Parse markup in file or URI * [tidy::parseString](tidy.parsestring) — Parse a document stored in a string * [tidy::repairFile](tidy.repairfile) — Repair a file and return it as a string * [tidy::repairString](tidy.repairstring) — Repair a string using an optionally provided configuration file * [tidy::root](tidy.root) — Returns a tidyNode object representing the root of the tidy parse tree
programming_docs
php SplObjectStorage::key SplObjectStorage::key ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplObjectStorage::key — Returns the index at which the iterator currently is ### Description ``` public SplObjectStorage::key(): int ``` Returns the index at which the iterator currently is. ### Parameters This function has no parameters. ### Return Values The index corresponding to the position of the iterator. ### Examples **Example #1 **SplObjectStorage::key()** example** ``` <?php $s = new SplObjectStorage(); $o1 = new StdClass; $o2 = new StdClass; $s->attach($o1, "d1"); $s->attach($o2, "d2"); $s->rewind(); while($s->valid()) {     $index  = $s->key();     $object = $s->current(); // similar to current($s)     var_dump($index);     var_dump($object);     $s->next(); } ?> ``` The above example will output something similar to: ``` int(0) object(stdClass)#2 (0) { } int(1) object(stdClass)#3 (0) { } ``` ### See Also * [SplObjectStorage::rewind()](splobjectstorage.rewind) - Rewind the iterator to the first storage element * [SplObjectStorage::current()](splobjectstorage.current) - Returns the current storage entry * [SplObjectStorage::next()](splobjectstorage.next) - Move to the next entry * [SplObjectStorage::valid()](splobjectstorage.valid) - Returns if the current iterator entry is valid php Ds\Map::pairs Ds\Map::pairs ============= (PECL ds >= 1.0.0) Ds\Map::pairs — Returns a sequence containing all the pairs of the map ### Description ``` public Ds\Map::pairs(): Ds\Sequence ``` Returns a **Ds\Sequence** containing all the pairs of the map. ### Parameters This function has no parameters. ### Return Values **Ds\Sequence** containing all the pairs of the map. ### Examples **Example #1 **Ds\Map::pairs()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->pairs()); ?> ``` The above example will output something similar to: ``` object(Ds\Map)#8 (3) { [0]=> object(Ds\Pair)#5 (2) { ["key"]=> string(1) "a" ["value"]=> int(1) } [1]=> object(Ds\Pair)#6 (2) { ["key"]=> string(1) "b" ["value"]=> int(2) } [2]=> object(Ds\Pair)#7 (2) { ["key"]=> string(1) "c" ["value"]=> int(3) } } p ``` php sqlsrv_commit sqlsrv\_commit ============== (No version information available, might only be in Git) sqlsrv\_commit — Commits a transaction that was begun with [sqlsrv\_begin\_transaction()](function.sqlsrv-begin-transaction) ### Description ``` sqlsrv_commit(resource $conn): bool ``` Commits a transaction that was begun with [sqlsrv\_begin\_transaction()](function.sqlsrv-begin-transaction). The connection is returned to auto-commit mode after **sqlsrv\_commit()** is called. The transaction that is committed includes all statements that were executed after the call to [sqlsrv\_begin\_transaction()](function.sqlsrv-begin-transaction). Explicit transactions should be started and committed or rolled back using these functions instead of executing SQL statements that begin and commit/roll back transactions. For more information, see [» SQLSRV Transactions](http://msdn.microsoft.com/en-us/library/cc296206.aspx). ### Parameters `conn` The connection on which the transaction is to be committed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **sqlsrv\_commit()** example** The following example demonstrates how to use **sqlsrv\_commit()** together with [sqlsrv\_begin\_transaction()](function.sqlsrv-begin-transaction) and [sqlsrv\_rollback()](function.sqlsrv-rollback). ``` <?php $serverName = "serverName\sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"userName", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) {     die( print_r( sqlsrv_errors(), true )); } /* Begin the transaction. */ if ( sqlsrv_begin_transaction( $conn ) === false ) {      die( print_r( sqlsrv_errors(), true )); } /* Initialize parameter values. */ $orderId = 1; $qty = 10; $productId = 100; /* Set up and execute the first query. */ $sql1 = "INSERT INTO OrdersTable (ID, Quantity, ProductID)          VALUES (?, ?, ?)"; $params1 = array( $orderId, $qty, $productId ); $stmt1 = sqlsrv_query( $conn, $sql1, $params1 ); /* Set up and execute the second query. */ $sql2 = "UPDATE InventoryTable           SET Quantity = (Quantity - ?)           WHERE ProductID = ?"; $params2 = array($qty, $productId); $stmt2 = sqlsrv_query( $conn, $sql2, $params2 ); /* If both queries were successful, commit the transaction. */ /* Otherwise, rollback the transaction. */ if( $stmt1 && $stmt2 ) {      sqlsrv_commit( $conn );      echo "Transaction committed.<br />"; } else {      sqlsrv_rollback( $conn );      echo "Transaction rolled back.<br />"; } ?> ``` ### See Also * [sqlsrv\_begin\_transaction()](function.sqlsrv-begin-transaction) - Begins a database transaction * [sqlsrv\_rollback()](function.sqlsrv-rollback) - Rolls back a transaction that was begun with sqlsrv\_begin\_transaction php gmp_popcount gmp\_popcount ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_popcount — Population count ### Description ``` gmp_popcount(GMP|int|string $num): int ``` Get the population count. ### Parameters `num` A [GMP](class.gmp) object, an int or a numeric string. ### Return Values The population count of `num`, as an int. ### Examples **Example #1 **gmp\_popcount()** example** ``` <?php $pop1 = gmp_init("10000101", 2); // 3 1's echo gmp_popcount($pop1) . "\n"; $pop2 = gmp_init("11111110", 2); // 7 1's echo gmp_popcount($pop2) . "\n"; ?> ``` The above example will output: ``` 3 7 ``` php radius_get_vendor_attr radius\_get\_vendor\_attr ========================= (PECL radius >= 1.1.0) radius\_get\_vendor\_attr — Extracts a vendor specific attribute ### Description ``` radius_get_vendor_attr(string $data): array ``` If [radius\_get\_attr()](function.radius-get-attr) returns **`RADIUS_VENDOR_SPECIFIC`**, **radius\_get\_vendor\_attr()** may be called to determine the vendor. ### Parameters `data` Input data ### Return Values Returns an associative array containing the attribute-type, vendor and the data, or **`false`** on error. ### Examples **Example #1 **radius\_get\_vendor\_attr()** example** ``` <?php while ($resa = radius_get_attr($res)) {     if (!is_array($resa)) {         printf ("Error getting attribute: %s\n",  radius_strerror($res));         exit;     }     $attr = $resa['attr'];     $data = $resa['data'];     printf("Got Attr:%d %d Bytes %s\n", $attr, strlen($data), bin2hex($data));     if ($attr == RADIUS_VENDOR_SPECIFIC) {         $resv = radius_get_vendor_attr($data);         if (is_array($resv)) {             $vendor = $resv['vendor'];             $attrv = $resv['attr'];             $datav = $resv['data'];                 printf("Got Vendor Attr:%d %d Bytes %s\n", $attrv, strlen($datav), bin2hex($datav));         }              } } ?> ``` ### See Also * [radius\_get\_attr()](function.radius-get-attr) - Extracts an attribute * [radius\_put\_vendor\_attr()](function.radius-put-vendor-attr) - Attaches a vendor specific binary attribute php GearmanTask::data GearmanTask::data ================= (PECL gearman >= 0.5.0) GearmanTask::data — Get data returned for a task ### Description ``` public GearmanTask::data(): string ``` Returns data being returned for a task by a worker. ### Parameters This function has no parameters. ### Return Values The serialized data, or **`false`** if no data is present. ### See Also * [GearmanTask::dataSize()](gearmantask.datasize) - Get the size of returned data php SplFileInfo::getFilename SplFileInfo::getFilename ======================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getFilename — Gets the filename ### Description ``` public SplFileInfo::getFilename(): string ``` Gets the filename without any path information. ### Parameters This function has no parameters. ### Return Values The filename. ### Examples **Example #1 **SplFileInfo::getFilename()** example** ``` <?php $info = new SplFileInfo('foo.txt'); var_dump($info->getFilename()); $info = new SplFileInfo('/path/to/foo.txt'); var_dump($info->getFilename()); $info = new SplFileInfo('http://www.php.net/'); var_dump($info->getFilename()); $info = new SplFileInfo('http://www.php.net/svn.php'); var_dump($info->getFilename()); ?> ``` The above example will output something similar to: ``` string(7) "foo.txt" string(7) "foo.txt" string(0) "" string(7) "svn.php" ``` ### See Also * [SplFileInfo::getBasename()](splfileinfo.getbasename) - Gets the base name of the file php Serializable::serialize Serializable::serialize ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) Serializable::serialize — String representation of object ### Description ``` public Serializable::serialize(): ?string ``` Should return the string representation of the object. ### Parameters This function has no parameters. ### Return Values Returns the string representation of the object or **`null`** ### Errors/Exceptions Throws [Exception](class.exception) when returning other types than strings and **`null`**. ### See Also * [\_\_sleep()](language.oop5.magic#object.sleep) * [\_\_serialize()](language.oop5.magic#object.serialize) php The RecursiveArrayIterator class The RecursiveArrayIterator class ================================ Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) This iterator allows to unset and modify values and keys while iterating over Arrays and Objects in the same way as the [ArrayIterator](class.arrayiterator). Additionally it is possible to iterate over the current iterator entry. Class synopsis -------------- class **RecursiveArrayIterator** extends [ArrayIterator](class.arrayiterator) implements [RecursiveIterator](class.recursiveiterator) { /\* Inherited constants \*/ public const int [ArrayIterator::STD\_PROP\_LIST](class.arrayiterator#arrayiterator.constants.std-prop-list); public const int [ArrayIterator::ARRAY\_AS\_PROPS](class.arrayiterator#arrayiterator.constants.array-as-props); /\* Constants \*/ public const int [CHILD\_ARRAYS\_ONLY](class.recursivearrayiterator#recursivearrayiterator.constants.child-arrays-only); /\* Methods \*/ ``` public getChildren(): ?RecursiveArrayIterator ``` ``` public hasChildren(): bool ``` /\* Inherited methods \*/ ``` public ArrayIterator::append(mixed $value): void ``` ``` public ArrayIterator::asort(int $flags = SORT_REGULAR): bool ``` ``` public ArrayIterator::count(): int ``` ``` public ArrayIterator::current(): mixed ``` ``` public ArrayIterator::getArrayCopy(): array ``` ``` public ArrayIterator::getFlags(): int ``` ``` public ArrayIterator::key(): string|int|null ``` ``` public ArrayIterator::ksort(int $flags = SORT_REGULAR): bool ``` ``` public ArrayIterator::natcasesort(): bool ``` ``` public ArrayIterator::natsort(): bool ``` ``` public ArrayIterator::next(): void ``` ``` public ArrayIterator::offsetExists(mixed $key): bool ``` ``` public ArrayIterator::offsetGet(mixed $key): mixed ``` ``` public ArrayIterator::offsetSet(mixed $key, mixed $value): void ``` ``` public ArrayIterator::offsetUnset(mixed $key): void ``` ``` public ArrayIterator::rewind(): void ``` ``` public ArrayIterator::seek(int $offset): void ``` ``` public ArrayIterator::serialize(): string ``` ``` public ArrayIterator::setFlags(int $flags): void ``` ``` public ArrayIterator::uasort(callable $callback): bool ``` ``` public ArrayIterator::uksort(callable $callback): bool ``` ``` public ArrayIterator::unserialize(string $data): void ``` ``` public ArrayIterator::valid(): bool ``` } Predefined Constants -------------------- RecursiveArrayIterator Flags ---------------------------- **`RecursiveArrayIterator::CHILD_ARRAYS_ONLY`** Treat only arrays (not objects) as having children for recursive iteration. Table of Contents ----------------- * [RecursiveArrayIterator::getChildren](recursivearrayiterator.getchildren) — Returns an iterator for the current entry if it is an array or an object * [RecursiveArrayIterator::hasChildren](recursivearrayiterator.haschildren) — Returns whether current entry is an array or an object php ImagickDraw::setClipRule ImagickDraw::setClipRule ======================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setClipRule — Set the polygon fill rule to be used by the clipping path ### Description ``` public ImagickDraw::setClipRule(int $fill_rule): bool ``` **Warning**This function is currently not documented; only its argument list is available. Set the polygon fill rule to be used by the clipping path. ### Parameters `fill_rule` One of the [FILLRULE](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.fillrule) constant (`imagick::FILLRULE_*`). ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setClipRule()** example** ``` <?php function setClipRule($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeOpacity(1);     $draw->setStrokeWidth(2);     //\Imagick::FILLRULE_EVENODD     //\Imagick::FILLRULE_NONZERO     $clipPathName = 'testClipPath';     $draw->pushClipPath($clipPathName);     $draw->setClipRule(\Imagick::FILLRULE_EVENODD);     $draw->rectangle(0, 0, 300, 500);     $draw->rectangle(200, 0, 500, 500);     $draw->popClipPath();     $draw->setClipPath($clipPathName);     $draw->rectangle(200, 200, 300, 300);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php extract extract ======= (PHP 4, PHP 5, PHP 7, PHP 8) extract — Import variables into the current symbol table from an array ### Description ``` extract(array &$array, int $flags = EXTR_OVERWRITE, string $prefix = ""): int ``` Import variables from an array into the current symbol table. Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. **Warning** Do not use **extract()** on untrusted data, like user input (e.g. [$\_GET](reserved.variables.get), [$\_FILES](reserved.variables.files)). ### Parameters `array` An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to `flags` and `prefix` parameters. You must use an associative array; a numerically indexed array will not produce results unless you use **`EXTR_PREFIX_ALL`** or **`EXTR_PREFIX_INVALID`**. `flags` The way invalid/numeric keys and collisions are treated is determined by the extraction `flags`. It can be one of the following values: **`EXTR_OVERWRITE`** If there is a collision, overwrite the existing variable. **`EXTR_SKIP`** If there is a collision, don't overwrite the existing variable. **`EXTR_PREFIX_SAME`** If there is a collision, prefix the variable name with `prefix`. **`EXTR_PREFIX_ALL`** Prefix all variable names with `prefix`. **`EXTR_PREFIX_INVALID`** Only prefix invalid/numeric variable names with `prefix`. **`EXTR_IF_EXISTS`** Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of [$\_REQUEST](reserved.variables.request), for example. **`EXTR_PREFIX_IF_EXISTS`** Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. **`EXTR_REFS`** Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the `array` parameter. You can use this flag on its own or combine it with any other flag by OR'ing the `flags`. If `flags` is not specified, it is assumed to be **`EXTR_OVERWRITE`**. `prefix` Note that `prefix` is only required if `flags` is **`EXTR_PREFIX_SAME`**, **`EXTR_PREFIX_ALL`**, **`EXTR_PREFIX_INVALID`** or **`EXTR_PREFIX_IF_EXISTS`**. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character. ### Return Values Returns the number of variables successfully imported into the symbol table. ### Examples **Example #1 **extract()** example** A possible use for **extract()** is to import into the symbol table variables contained in an associative array returned by [wddx\_deserialize()](function.wddx-deserialize). ``` <?php /* Suppose that $var_array is an array returned from    wddx_deserialize */ $size = "large"; $var_array = array("color" => "blue",                    "size"  => "medium",                    "shape" => "sphere"); extract($var_array, EXTR_PREFIX_SAME, "wddx"); echo "$color, $size, $shape, $wddx_size\n"; ?> ``` The above example will output: ``` blue, large, sphere, medium ``` The $size wasn't overwritten because we specified **`EXTR_PREFIX_SAME`**, which resulted in $wddx\_size being created. If **`EXTR_SKIP`** was specified, then $wddx\_size wouldn't even have been created. **`EXTR_OVERWRITE`** would have caused $size to have value "medium", and **`EXTR_PREFIX_ALL`** would result in new variables being named $wddx\_color, $wddx\_size, and $wddx\_shape. ### Notes **Warning** Do not use **extract()** on untrusted data, like user input (i.e. [$\_GET](reserved.variables.get), [$\_FILES](reserved.variables.files), etc.). If you do, make sure you use one of the non-overwriting `flags` values such as **`EXTR_SKIP`** and be aware that you should extract in the same order that's defined in [variables\_order](https://www.php.net/manual/en/ini.core.php#ini.variables-order) within the [php.ini](https://www.php.net/manual/en/ini.php). ### See Also * [compact()](function.compact) - Create array containing variables and their values * [list()](function.list) - Assign variables as if they were an array php SolrQuery::addFilterQuery SolrQuery::addFilterQuery ========================= (PECL solr >= 0.9.2) SolrQuery::addFilterQuery — Specifies a filter query ### Description ``` public SolrQuery::addFilterQuery(string $fq): SolrQuery ``` Specifies a filter query ### Parameters `fq` The filter query ### Return Values Returns the current SolrQuery object. ### Examples **Example #1 **SolrQuery::addFilterQuery()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); $query = new SolrQuery(); $query->setQuery('*:*'); $query->addFilterQuery('color:blue,green'); $query_response = $client->query($query); $response = $query_response->getResponse(); print_r($response['facet_counts']['facet_fields']); ?> ``` The above example will output something similar to: ``` &fq=color:blue,green ``` php Gmagick::charcoalimage Gmagick::charcoalimage ====================== (PECL gmagick >= Unknown) Gmagick::charcoalimage — Simulates a charcoal drawing ### Description ``` public Gmagick::charcoalimage(float $radius, float $sigma): Gmagick ``` Simulates a charcoal drawing. ### Parameters `radius` The radius of the Gaussian, in pixels, not counting the center pixel. `sigma` The standard deviation of the Gaussian, in pixels. ### Return Values The [Gmagick](class.gmagick) object with charcoal simulation. ### Errors/Exceptions Throws an **GmagickException** on error.
programming_docs
php stats_cdf_binomial stats\_cdf\_binomial ==================== (PECL stats >= 1.0.0) stats\_cdf\_binomial — Calculates any one parameter of the binomial distribution given values for the others ### Description ``` stats_cdf_binomial( float $par1, float $par2, float $par3, int $which ): float ``` Returns the cumulative distribution function, its inverse, or one of its parameters, of the binomial distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`. The following table lists the return value and parameters by `which`. CDF, x, n, and p denotes cumulative distribution function, the number of successes, the number of trials, and the success rate for each trial, respectively. **Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` | | --- | --- | --- | --- | --- | | 1 | CDF | x | n | p | | 2 | x | CDF | n | p | | 3 | n | x | CDF | p | | 4 | p | x | CDF | n | ### Parameters `par1` The first parameter `par2` The second parameter `par3` The third parameter `which` The flag to determine what to be calculated ### Return Values Returns CDF, x, n, or p, determined by `which`. php Imagick::setInterlaceScheme Imagick::setInterlaceScheme =========================== (PECL imagick 2, PECL imagick 3) Imagick::setInterlaceScheme — Sets the image compression ### Description ``` public Imagick::setInterlaceScheme(int $interlace_scheme): bool ``` Sets the image compression. ### Parameters `interlace_scheme` ### Return Values Returns **`true`** on success. php JsonSerializable::jsonSerialize JsonSerializable::jsonSerialize =============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) JsonSerializable::jsonSerialize — Specify data which should be serialized to JSON ### Description ``` public JsonSerializable::jsonSerialize(): mixed ``` Serializes the object to a value that can be serialized natively by [json\_encode()](function.json-encode). ### Parameters This function has no parameters. ### Return Values Returns data which can be serialized by [json\_encode()](function.json-encode), which is a value of any type other than a [resource](language.types.resource). ### Examples **Example #1 **JsonSerializable::jsonSerialize()** example returning an array** ``` <?php class ArrayValue implements JsonSerializable {     public function __construct(array $array) {         $this->array = $array;     }     public function jsonSerialize() {         return $this->array;     } } $array = [1, 2, 3]; echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT); ?> ``` The above example will output: ``` [ 1, 2, 3 ] ``` **Example #2 **JsonSerializable::jsonSerialize()** example returning an associative array** ``` <?php class ArrayValue implements JsonSerializable {     public function __construct(array $array) {         $this->array = $array;     }     public function jsonSerialize() {         return $this->array;     } } $array = ['foo' => 'bar', 'quux' => 'baz']; echo json_encode(new ArrayValue($array), JSON_PRETTY_PRINT); ?> ``` The above example will output: ``` { "foo": "bar", "quux": "baz" } ``` **Example #3 **JsonSerializable::jsonSerialize()** example returning an int** ``` <?php class IntegerValue implements JsonSerializable {     public function __construct($number) {         $this->number = (integer) $number;     }     public function jsonSerialize() {         return $this->number;     } } echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT); ?> ``` The above example will output: ``` 1 ``` **Example #4 **JsonSerializable::jsonSerialize()** example returning a string** ``` <?php class StringValue implements JsonSerializable {     public function __construct($string) {         $this->string = (string) $string;     }     public function jsonSerialize() {         return $this->string;     } } echo json_encode(new StringValue('Hello!'), JSON_PRETTY_PRINT); ?> ``` The above example will output: ``` "Hello!" ``` php Ds\Sequence::reduce Ds\Sequence::reduce =================== (PECL ds >= 1.0.0) Ds\Sequence::reduce — Reduces the sequence to a single value using a callback function ### Description ``` abstract public Ds\Sequence::reduce(callable $callback, mixed $initial = ?): mixed ``` Reduces the sequence to a single value using a callback function. ### Parameters `callback` ``` callback(mixed $carry, mixed $value): mixed ``` `carry` The return value of the previous callback, or `initial` if it's the first iteration. `value` The value of the current iteration. `initial` The initial value of the carry value. Can be **`null`**. ### Return Values The return value of the final callback. ### Examples **Example #1 **Ds\Sequence::reduce()** with initial value example** ``` <?php $sequence = new \Ds\Vector([1, 2, 3]); $callback = function($carry, $value) {     return $carry * $value; }; var_dump($sequence->reduce($callback, 5)); // Iterations: // // $carry = $initial = 5 // // $carry = $carry * 1 =  5 // $carry = $carry * 2 = 10 // $carry = $carry * 3 = 30 ?> ``` The above example will output something similar to: ``` int(30) ``` **Example #2 **Ds\Sequence::reduce()** without an initial value example** ``` <?php $sequence = new \Ds\Vector([1, 2, 3]); var_dump($sequence->reduce(function($carry, $value) {     return $carry + $value + 5; })); // Iterations: // // $carry = $initial = null // // $carry = $carry + 1 + 5 =  6 // $carry = $carry + 2 + 5 = 13 // $carry = $carry + 3 + 5 = 21 ?> ``` The above example will output something similar to: ``` int(21) ``` php imap_header imap\_header ============ (PHP 4, PHP 5, PHP 7) imap\_header — Alias of [imap\_headerinfo()](function.imap-headerinfo) **Warning**This alias is *REMOVED* as of PHP 8.0.0. ### Description This function is an alias of: [imap\_headerinfo()](function.imap-headerinfo). php Imagick::setImageExtent Imagick::setImageExtent ======================= (PECL imagick 2, PECL imagick 3) Imagick::setImageExtent — Sets the image size ### Description ``` public Imagick::setImageExtent(int $columns, int $rows): bool ``` Sets the image size (i.e. columns & rows). ### Parameters `columns` `rows` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php IntlCalendar::isSet IntlCalendar::isSet =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::isSet — Whether a field is set ### Description Object-oriented style ``` public IntlCalendar::isSet(int $field): bool ``` Procedural style ``` intlcal_is_set(IntlCalendar $calendar, int $field): bool ``` Returns whether a field is set (as opposed to [clear](intlcalendar.clear)). Set fields take priority over unset fields and their default values when the date/time is being calculated. Fields set later take priority over fields set earlier. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values Assuming there are no argument errors, returns **`true`** if the field is set. ### Examples See the example on [IntlCalendar::clear()](intlcalendar.clear). ### See Also * [IntlCalendar::clear()](intlcalendar.clear) - Clear a field or all fields * [IntlCalendar::set()](intlcalendar.set) - Set a time field or several common fields at once php SolrQuery::setHighlightUsePhraseHighlighter SolrQuery::setHighlightUsePhraseHighlighter =========================================== (PECL solr >= 0.9.2) SolrQuery::setHighlightUsePhraseHighlighter — Whether to highlight phrase terms only when they appear within the query phrase ### Description ``` public SolrQuery::setHighlightUsePhraseHighlighter(bool $flag): SolrQuery ``` Sets whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document ### Parameters `value` Whether or not to use SpanScorer to highlight phrase terms only when they appear within the query phrase in the document ### Return Values Returns the current SolrQuery object, if the return value is used. php stream_context_set_params stream\_context\_set\_params ============================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_context\_set\_params — Set parameters for a stream/wrapper/context ### Description ``` stream_context_set_params(resource $context, array $params): bool ``` Sets parameters on the specified context. ### Parameters `context` The stream or context to apply the parameters too. `params` An associative array of parameters to be set in the following format: `$params['paramname'] = "paramvalue";`. **Supported parameters**| Parameter | Purpose | | --- | --- | | `notification` | Name of user-defined callback function to be called whenever a stream triggers a notification. Only supported for [http://](https://www.php.net/manual/en/wrappers.http.php) and [ftp://](https://www.php.net/manual/en/wrappers.ftp.php) stream wrappers. | | `options` | Array of options as in [context options and parameters](https://www.php.net/manual/en/context.php). | ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [stream\_notification\_callback()](function.stream-notification-callback) - A callback function for the notification context parameter php ReflectionFunctionAbstract::getAttributes ReflectionFunctionAbstract::getAttributes ========================================= (PHP 8) ReflectionFunctionAbstract::getAttributes — Gets Attributes ### Description ``` public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array ``` Returns all attributes declared on this function or method as an array of [ReflectionAttribute](class.reflectionattribute). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `flags` ### Return Values Array of attributes, as a [ReflectionAttribute](class.reflectionattribute) object. ### See Also * [ReflectionClass::getAttributes()](reflectionclass.getattributes) - Gets Attributes * [ReflectionClassConstant::getAttributes()](reflectionclassconstant.getattributes) - Gets Attributes * [ReflectionParameter::getAttributes()](reflectionparameter.getattributes) - Gets Attributes * [ReflectionProperty::getAttributes()](reflectionproperty.getattributes) - Gets Attributes php Imagick::oilPaintImage Imagick::oilPaintImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::oilPaintImage — Simulates an oil painting ### Description ``` public Imagick::oilPaintImage(float $radius): bool ``` Applies a special effect filter that simulates an oil painting. Each pixel is replaced by the most frequent color occurring in a circular region defined by radius. ### Parameters `radius` The radius of the circular neighborhood. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::oilPaintImage()**** ``` <?php function oilPaintImage($imagePath, $radius) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->oilPaintImage($radius);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php eio_set_max_idle eio\_set\_max\_idle =================== (PECL eio >= 0.0.1dev) eio\_set\_max\_idle — Set maximum number of idle threads ### Description ``` eio_set_max_idle(int $nthreads): void ``` ### Parameters `nthreads` Number of idle threads. ### Return Values No value is returned. ### See Also * [eio\_nthreads()](function.eio-nthreads) - Returns number of threads currently in use * [eio\_set\_min\_parallel()](function.eio-set-min-parallel) - Set minimum parallel thread number * [eio\_set\_max\_parallel()](function.eio-set-max-parallel) - Set maximum parallel threads php uopz_get_mock uopz\_get\_mock =============== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_get\_mock — Get the current mock for a class ### Description ``` uopz_get_mock(string $class): mixed ``` Returns the current mock for `class`. ### Parameters `class` The name of the mocked class. ### Return Values Either a string containing the name of the mock, or an object, or **`null`** if no mock has been set. ### Examples **Example #1 **uopz\_get\_mock()** example** ``` <?php class A {     public static function who() {         echo "A";     } } class mockA {     public static function who() {         echo "mockA";     } } uopz_set_mock(A::class, mockA::class); echo uopz_get_mock(A::class); ?> ``` The above example will output: ``` mockA ``` ### See Also * [uopz\_set\_mock()](function.uopz-set-mock) - Use mock instead of class for new objects * [uopz\_unset\_mock()](function.uopz-unset-mock) - Unset previously set mock php GearmanClient::data GearmanClient::data =================== (PECL gearman <= 0.5.0) GearmanClient::data — Get the application data (deprecated) ### Description ``` public GearmanClient::data(): string ``` Get the application data previously set with [GearmanClient::setData()](gearmanclient.setdata). > > **Note**: > > > This method was replaced by [GearmanClient::setContext()](gearmanclient.setcontext) in the 0.6.0 release of the Gearman extension. > > ### Parameters This function has no parameters. ### Return Values The same string data set with [GearmanClient::setData()](gearmanclient.setdata) ### See Also * [GearmanClient::setData()](gearmanclient.setdata) - Set application data (deprecated) php The Reflection class The Reflection class ==================== Introduction ------------ (PHP 5, PHP 7, PHP 8) The reflection class. Class synopsis -------------- class **Reflection** { /\* Methods \*/ ``` public static export(Reflector $reflector, bool $return = false): string ``` ``` public static getModifierNames(int $modifiers): array ``` } Table of Contents ----------------- * [Reflection::export](reflection.export) — Exports * [Reflection::getModifierNames](reflection.getmodifiernames) — Gets modifier names php array_unique array\_unique ============= (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) array\_unique — Removes duplicate values from an array ### Description ``` array_unique(array $array, int $flags = SORT_STRING): array ``` Takes an input `array` and returns a new array without duplicate values. Note that keys are preserved. If multiple elements compare equal under the given `flags`, then the key and value of the first equal element will be retained. > **Note**: Two elements are considered equal if and only if `(string) $elem1 === (string) $elem2` i.e. when the string representation is the same, the first element will be used. > > ### Parameters `array` The input array. `flags` The optional second parameter `flags` may be used to modify the sorting behavior using these values: Sorting type flags: * **`SORT_REGULAR`** - compare items normally (don't change types) * **`SORT_NUMERIC`** - compare items numerically * **`SORT_STRING`** - compare items as strings * **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. ### Return Values Returns the filtered array. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | If `flags` is **`SORT_STRING`**, formerly `array` has been copied and non-unique elements have been removed (without packing the array afterwards), but now a new array is built by adding the unique elements. This can result in different numeric indexes. | ### Examples **Example #1 **array\_unique()** example** ``` <?php $input = array("a" => "green", "red", "b" => "green", "blue", "red"); $result = array_unique($input); print_r($result); ?> ``` The above example will output: ``` Array ( [a] => green [0] => red [1] => blue ) ``` **Example #2 **array\_unique()** and types** ``` <?php $input = array(4, "4", "3", 4, 3, "3"); $result = array_unique($input); var_dump($result); ?> ``` The above example will output: ``` array(2) { [0] => int(4) [2] => string(1) "3" } ``` ### Notes > **Note**: Note that **array\_unique()** is not intended to work on multi dimensional arrays. > > ### See Also * [array\_count\_values()](function.array-count-values) - Counts all the values of an array php yaml_emit_file yaml\_emit\_file ================ (PECL yaml >= 0.5.0) yaml\_emit\_file — Send the YAML representation of a value to a file ### Description ``` yaml_emit_file( string $filename, mixed $data, int $encoding = YAML_ANY_ENCODING, int $linebreak = YAML_ANY_BREAK, array $callbacks = null ): bool ``` Generate a YAML representation of the provided `data` in the `filename`. ### Parameters `filename` Path to the file. `data` The `data` being encoded. Can be any type except a resource. `encoding` Output character encoding chosen from **`YAML_ANY_ENCODING`**, **`YAML_UTF8_ENCODING`**, **`YAML_UTF16LE_ENCODING`**, **`YAML_UTF16BE_ENCODING`**. `linebreak` Output linebreak style chosen from **`YAML_ANY_BREAK`**, **`YAML_CR_BREAK`**, **`YAML_LN_BREAK`**, **`YAML_CRLN_BREAK`**. `callbacks` Content handlers for emitting YAML nodes. Associative array of classname => [callable](language.types.callable) mappings. See [emit callbacks](https://www.php.net/manual/en/yaml.callbacks.emit.php) for more details. ### Return Values Returns **`true`** on success. ### Changelog | Version | Description | | --- | --- | | PECL yaml 1.1.0 | The `callbacks` parameter was added. | ### See Also * [yaml\_emit()](function.yaml-emit) - Returns the YAML representation of a value * [yaml\_parse()](function.yaml-parse) - Parse a YAML stream php stream_socket_server stream\_socket\_server ====================== (PHP 5, PHP 7, PHP 8) stream\_socket\_server — Create an Internet or Unix domain server socket ### Description ``` stream_socket_server( string $address, int &$error_code = null, string &$error_message = null, int $flags = STREAM_SERVER_BIND | STREAM_SERVER_LISTEN, ?resource $context = null ): resource|false ``` Creates a stream or datagram socket on the specified `address`. This function only creates a socket, to begin accepting connections use [stream\_socket\_accept()](function.stream-socket-accept). ### Parameters `address` The type of socket created is determined by the transport specified using standard URL formatting: `transport://target`. For Internet Domain sockets (**`AF_INET`**) such as TCP and UDP, the `target` portion of the `remote_socket` parameter should consist of a hostname or IP address followed by a colon and a port number. For Unix domain sockets, the `target` portion should point to the socket file on the filesystem. Depending on the environment, Unix domain sockets may not be available. A list of available transports can be retrieved using [stream\_get\_transports()](function.stream-get-transports). See [List of Supported Socket Transports](https://www.php.net/manual/en/transports.php) for a list of bulitin transports. `error_code` If the optional `error_code` and `error_message` arguments are present they will be set to indicate the actual system level error that occurred in the system-level `socket()`, `bind()`, and `listen()` calls. If the value returned in `error_code` is `0` and the function returned **`false`**, it is an indication that the error occurred before the `bind()` call. This is most likely due to a problem initializing the socket. Note that the `error_code` and `error_message` arguments will always be passed by reference. `error_message` See `error_code` description. `flags` A bitmask field which may be set to any combination of socket creation flags. > > **Note**: > > > For UDP sockets, you must use **`STREAM_SERVER_BIND`** as the `flags` parameter. > > `context` ### Return Values Returns the created stream, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `context` is nullable now. | ### Examples **Example #1 Using TCP server sockets** ``` <?php $socket = stream_socket_server("tcp://0.0.0.0:8000", $errno, $errstr); if (!$socket) {   echo "$errstr ($errno)<br />\n"; } else {   while ($conn = stream_socket_accept($socket)) {     fwrite($conn, 'The local time is ' . date('n/j/Y g:i a') . "\n");     fclose($conn);   }   fclose($socket); } ?> ``` The example below shows how to act as a time server which can respond to time queries as shown in an example on [stream\_socket\_client()](function.stream-socket-client). > **Note**: Most systems require root access to create a server socket on a port below 1024. > > **Example #2 Using UDP server sockets** ``` <?php $socket = stream_socket_server("udp://127.0.0.1:1113", $errno, $errstr, STREAM_SERVER_BIND); if (!$socket) {     die("$errstr ($errno)"); } do {     $pkt = stream_socket_recvfrom($socket, 1, 0, $peer);     echo "$peer\n";     stream_socket_sendto($socket, date("D M j H:i:s Y\r\n"), 0, $peer); } while ($pkt !== false); ?> ``` ### Notes > **Note**: When specifying a numerical IPv6 address (e.g. `fe80::1`), you must enclose the IP in square brackets—for example, `tcp://[fe80::1]:80`. > > ### See Also * [stream\_socket\_client()](function.stream-socket-client) - Open Internet or Unix domain socket connection * [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream * [stream\_set\_timeout()](function.stream-set-timeout) - Set timeout period on a stream * [fgets()](function.fgets) - Gets line from file pointer * [fgetss()](function.fgetss) - Gets line from file pointer and strip HTML tags * [fwrite()](function.fwrite) - Binary-safe file write * [fclose()](function.fclose) - Closes an open file pointer * [feof()](function.feof) - Tests for end-of-file on a file pointer * [Curl extension](https://www.php.net/manual/en/ref.curl.php)
programming_docs
php SolrClient::addDocuments SolrClient::addDocuments ======================== (PECL solr >= 0.9.2) SolrClient::addDocuments — Adds a collection of SolrInputDocument instances to the index ### Description ``` public SolrClient::addDocuments(array $docs, bool $overwrite = true, int $commitWithin = 0): void ``` Adds a collection of documents to the index. ### Parameters `docs` An array containing the collection of SolrInputDocument instances. This array must be an actual variable. `overwrite` Whether to overwrite existing documents or not. If **`false`** there will be duplicates (several documents with the same ID). **Warning** PECL Solr < 2.0 $allowDups was used instead of $overwrite, which does the same functionality with exact opposite bool flag. $allowDups = false is the same as $overwrite = true `commitWithin` Number of milliseconds within which to auto commit this document. Available since Solr 1.4 . Default (0) means disabled. When this value specified, it leaves the control of when to do the commit to Solr itself, optimizing number of commits to a minimum while still fulfilling the update latency requirements, and Solr will automatically do a commit when the oldest add in the buffer is due. ### Return Values Returns a [SolrUpdateResponse](class.solrupdateresponse) object or throws an exception on failure. ### Errors/Exceptions Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to process the request. ### Examples **Example #1 **SolrClient::addDocuments()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); $doc = new SolrInputDocument(); $doc->addField('id', 334455); $doc->addField('cat', 'Software'); $doc->addField('cat', 'Lucene'); $doc2 = clone $doc; $doc2->deleteField('id'); $doc2->addField('id', 334456); $docs = array($doc, $doc2); $updateResponse = $client->addDocuments($docs); // no changes will be written to disk unless $commitWithin is passed or SolrClient::commit is called print_r($updateResponse->getResponse()); ?> ``` The above example will output something similar to: ``` SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 2 ) ) ``` ### See Also * [SolrClient::addDocument()](solrclient.adddocument) - Adds a document to the index * [SolrClient::commit()](solrclient.commit) - Finalizes all add/deletes made to the index php Locale::composeLocale Locale::composeLocale ===================== locale\_compose =============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::composeLocale -- locale\_compose — Returns a correctly ordered and delimited locale ID ### Description Object-oriented style ``` public static Locale::composeLocale(array $subtags): string|false ``` Procedural style ``` locale_compose(array $subtags): string|false ``` Returns a correctly ordered and delimited locale ID the keys identify the particular locale ID subtags, and the values are the associated subtag values. ### Parameters `subtags` An array containing a list of key-value pairs, where the keys identify the particular locale ID subtags, and the values are the associated subtag values. > > **Note**: > > > The `'variant'` and `'private'` subtags can take maximum 15 values whereas `'extlang'` can take maximum 3 values. For instance, variants are allowed with the suffix ranging from 0-14. Hence the keys for the input array can be `variant0`, `variant1`, …,`variant14`. In the returned locale id, the subtag is ordered by suffix resulting in `variant0` followed by `variant1` followed by `variant2` and so on. > > Alternatively, the `'variant'`, `'private'` and `'extlang'` values can be specified as array under specific key (e.g. `'variant'`). In this case no limits on the number of recognized subtags apply. > > ### Return Values The corresponding locale identifier, or **`false`** when `subtags` is empty. ### Examples **Example #1 **locale\_compose()** example** ``` <?php $arr = array(     'language'=>'en',     'script'  =>'Hans',     'region'  =>'CN',     'variant2'=>'rozaj',     'variant1'=>'nedis',     'private1'=>'prv1',     'private2'=>'prv2', ); echo locale_compose($arr); ?> ``` **Example #2 OO example** ``` <?php $arr = array(     'language'=>'en' ,     'script'  =>'Hans',     'region'  =>'CN',     'variant2'=>'rozaj',     'variant1'=>'nedis',     'private1'=>'prv1',     'private2'=>'prv2', ); echo Locale::composeLocale($arr); ?> ``` The above example will output: ``` Locale: en_Hans_CN_nedis_rozaj_x_prv1_prv2 ``` **Example #3 Subtag limits** If `subtags` are given as separate keys with numeric suffix, unsupported keys are silently ignored (in this case `'extlang3'`), and ordered in the result by numeric suffix. There are no limits, if subtags are given as array; the order is as given. ``` <?php $arr = array(     'language' => 'en',     'script'   => 'Hans',     'region'   => 'CN',     'extlang3' => 'd',     'extlang2' => 'c',     'extlang1' => 'b',     'extlang0' => 'a', ); echo locale_compose($arr), PHP_EOL; $arr = array(     'language' => 'en',     'script'   => 'Hans',     'region'   => 'CN',     'extlang'  => ['a', 'b', 'c', 'd'], ); echo locale_compose($arr), PHP_EOL; ?> ``` The above example will output: ``` en_a_b_c_Hans_CN en_a_b_c_d_Hans_CN ``` ### See Also * [locale\_parse()](locale.parselocale) - Returns a key-value array of locale ID subtag elements php array_filter array\_filter ============= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) array\_filter — Filters elements of an array using a callback function ### Description ``` array_filter(array $array, ?callable $callback = null, int $mode = 0): array ``` Iterates over each value in the `array` passing them to the `callback` function. If the `callback` function returns **`true`**, the current value from `array` is returned into the result array. Array keys are preserved, and may result in gaps if the `array` was indexed. The result array can be reindexed using the [array\_values()](function.array-values) function. ### Parameters `array` The array to iterate over `callback` The callback function to use If no `callback` is supplied, all empty entries of `array` will be removed. See [empty()](function.empty) for how PHP defines empty in this case. `mode` Flag determining what arguments are sent to `callback`: * **`ARRAY_FILTER_USE_KEY`** - pass key as the only argument to `callback` instead of the value * **`ARRAY_FILTER_USE_BOTH`** - pass both value and key as arguments to `callback` instead of the value Default is `0` which will pass value as the only argument to `callback` instead. ### Return Values Returns the filtered array. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `callback` is nullable now. | | 8.0.0 | If `callback` expects a parameter to be passed by reference, this function will now emit an **`E_WARNING`**. | ### Examples **Example #1 **array\_filter()** example** ``` <?php function odd($var) {     // returns whether the input integer is odd     return $var & 1; } function even($var) {     // returns whether the input integer is even     return !($var & 1); } $array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; $array2 = [6, 7, 8, 9, 10, 11, 12]; echo "Odd :\n"; print_r(array_filter($array1, "odd")); echo "Even:\n"; print_r(array_filter($array2, "even")); ?> ``` The above example will output: ``` Odd : Array ( [a] => 1 [c] => 3 [e] => 5 ) Even: Array ( [0] => 6 [2] => 8 [4] => 10 [6] => 12 ) ``` **Example #2 **array\_filter()** without `callback`** ``` <?php $entry = [     0 => 'foo',     1 => false,     2 => -1,     3 => null,     4 => '',     5 => '0',     6 => 0, ]; print_r(array_filter($entry)); ?> ``` The above example will output: ``` Array ( [0] => foo [2] => -1 ) ``` **Example #3 **array\_filter()** with `mode`** ``` <?php $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; var_dump(array_filter($arr, function($k) {     return $k == 'b'; }, ARRAY_FILTER_USE_KEY)); var_dump(array_filter($arr, function($v, $k) {     return $k == 'b' || $v == 4; }, ARRAY_FILTER_USE_BOTH)); ?> ``` The above example will output: ``` array(1) { ["b"]=> int(2) } array(2) { ["b"]=> int(2) ["d"]=> int(4) } ``` ### Notes **Caution** If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined. ### See Also * [array\_intersect()](function.array-intersect) - Computes the intersection of arrays * [array\_map()](function.array-map) - Applies the callback to the elements of the given arrays * [array\_reduce()](function.array-reduce) - Iteratively reduce the array to a single value using a callback function * [array\_walk()](function.array-walk) - Apply a user supplied function to every member of an array php Ds\Vector::copy Ds\Vector::copy =============== (PECL ds >= 1.0.0) Ds\Vector::copy — Returns a shallow copy of the vector ### Description ``` public Ds\Vector::copy(): Ds\Vector ``` Returns a shallow copy of the vector. ### Parameters This function has no parameters. ### Return Values Returns a shallow copy of the vector. ### Examples **Example #1 **Ds\Vector::copy()** example** ``` <?php $a = new \Ds\Vector([1, 2, 3]); $b = $a->copy(); // Updating the copy doesn't affect the original $b->push(4); print_r($a); print_r($b); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ``` php RecursiveIteratorIterator::next RecursiveIteratorIterator::next =============================== (PHP 5, PHP 7, PHP 8) RecursiveIteratorIterator::next — Move forward to the next element ### Description ``` public RecursiveIteratorIterator::next(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php GmagickDraw::annotate GmagickDraw::annotate ===================== (PECL gmagick >= Unknown) GmagickDraw::annotate — Draws text on the image ### Description ``` public GmagickDraw::annotate(float $x, float $y, string $text): GmagickDraw ``` Draws text on the image. ### Parameters `x` x ordinate to left of text `y` y ordinate to text baseline `text` text to draw ### Return Values The [GmagickDraw](class.gmagickdraw) object. php The ImagickKernel class The ImagickKernel class ======================= Introduction ------------ (PECL imagick >= 3.3.0) Class synopsis -------------- class **ImagickKernel** { /\* Methods \*/ ``` public addKernel(ImagickKernel $ImagickKernel): void ``` ``` public addUnityKernel(float $scale): void ``` ``` public static fromBuiltin(int $kernelType, string $kernelString): ImagickKernel ``` ``` public static fromMatrix(array $matrix, array $origin = ?): ImagickKernel ``` ``` public getMatrix(): array ``` ``` public scale(float $scale, int $normalizeFlag = ?): void ``` ``` public separate(): array ``` } Table of Contents ----------------- * [ImagickKernel::addKernel](imagickkernel.addkernel) — Description * [ImagickKernel::addUnityKernel](imagickkernel.addunitykernel) — Description * [ImagickKernel::fromBuiltIn](imagickkernel.frombuiltin) — Description * [ImagickKernel::fromMatrix](imagickkernel.frommatrix) — Description * [ImagickKernel::getMatrix](imagickkernel.getmatrix) — Description * [ImagickKernel::scale](imagickkernel.scale) — Description * [ImagickKernel::separate](imagickkernel.separate) — Description php Closure::call Closure::call ============= (PHP 7, PHP 8) Closure::call — Binds and calls the closure ### Description ``` public Closure::call(object $newThis, mixed ...$args): mixed ``` Temporarily binds the closure to `newThis`, and calls it with any given parameters. ### Parameters `newThis` The object to bind the closure to for the duration of the call. `args` Zero or more parameters, which will be given as parameters to the closure. ### Return Values Returns the return value of the closure. ### Examples **Example #1 **Closure::call()** example** ``` <?php class Value {     protected $value;     public function __construct($value) {         $this->value = $value;     }     public function getValue() {         return $this->value;     } } $three = new Value(3); $four = new Value(4); $closure = function ($delta) { var_dump($this->getValue() + $delta); }; $closure->call($three, 4); $closure->call($four, 4); ?> ``` The above example will output: ``` int(7) int(8) ``` php mysqli_connect mysqli\_connect =============== (PHP 5, PHP 7, PHP 8) mysqli\_connect — Alias of [mysqli::\_\_construct()](mysqli.construct) ### Description This function is an alias of: [mysqli::\_\_construct()](mysqli.construct) > > **Note**: > > > If mysqli exception mode is not enabled and a connection fails, then **mysqli\_connect()** returns **`false`** instead of an object. The [mysqli\_connect\_error()](mysqli.connect-error) function can be used to fetch the connection error. > > php XSLTProcessor::setParameter XSLTProcessor::setParameter =========================== (PHP 5, PHP 7, PHP 8) XSLTProcessor::setParameter — Set value for a parameter ### Description ``` public XSLTProcessor::setParameter(string $namespace, string $name, string $value): bool ``` ``` public XSLTProcessor::setParameter(string $namespace, array $options): bool ``` Sets the value of one or more parameters to be used in subsequent transformations with [XSLTProcessor](class.xsltprocessor). If the parameter doesn't exist in the stylesheet it will be ignored. ### Parameters `namespace` The namespace URI of the XSLT parameter. `name` The local name of the XSLT parameter. `value` The new value of the XSLT parameter. `options` An array of `name => value` pairs. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Changing the owner before the transformation** ``` <?php $collections = array(     'Marc Rutkowski' => 'marc',     'Olivier Parmentier' => 'olivier' ); $xsl = new DOMDocument; $xsl->load('collection.xsl'); // Configure the transformer $proc = new XSLTProcessor; $proc->importStyleSheet($xsl); // attach the xsl rules foreach ($collections as $name => $file) {     // Load the XML source     $xml = new DOMDocument;     $xml->load('collection_' . $file . '.xml');     $proc->setParameter('', 'owner', $name);     $proc->transformToURI($xml, 'file:///tmp/' . $file . '.html'); } ?> ``` ### See Also * [XSLTProcessor::getParameter()](xsltprocessor.getparameter) - Get value of a parameter * [XSLTProcessor::removeParameter()](xsltprocessor.removeparameter) - Remove parameter php apache_getenv apache\_getenv ============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) apache\_getenv — Get an Apache subprocess\_env variable ### Description ``` apache_getenv(string $variable, bool $walk_to_top = false): string|false ``` Retrieve an Apache environment variable specified by `variable`. ### Parameters `variable` The Apache environment variable `walk_to_top` Whether to get the top-level variable available to all Apache layers. ### Return Values The value of the Apache environment variable on success, or **`false`** on failure ### Examples **Example #1 **apache\_getenv()** example** The example above shows how to retrieve the value of the Apache environment variable SERVER\_ADDR. ``` <?php $ret = apache_getenv("SERVER_ADDR"); echo $ret; ?> ``` The above example will output something similar to: ``` 42.24.42.240 ``` ### See Also * [apache\_setenv()](function.apache-setenv) - Set an Apache subprocess\_env variable * [getenv()](function.getenv) - Gets the value of an environment variable * [Superglobals](language.variables.superglobals) php SplFileObject::eof SplFileObject::eof ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::eof — Reached end of file ### Description ``` public SplFileObject::eof(): bool ``` Determine whether the end of file has been reached ### Parameters This function has no parameters. ### Return Values Returns **`true`** if file is at EOF, **`false`** otherwise. ### Examples **Example #1 **SplFileObject::eof()** example** ``` <?php $file = new SplFileObject("fruits.txt"); while ( ! $file->eof()) {     echo $file->fgets(); } ?> ``` The above example will output something similar to: ``` apple banana cherry date elderberry ``` ### See Also * [SplFileObject::valid()](splfileobject.valid) - Not at EOF * [feof()](function.feof) - Tests for end-of-file on a file pointer php Imagick::setFormat Imagick::setFormat ================== (PECL imagick 2, PECL imagick 3) Imagick::setFormat — Sets the format of the Imagick object ### Description ``` public Imagick::setFormat(string $format): bool ``` Sets the format of the Imagick object. ### Parameters `format` ### Return Values Returns **`true`** on success. php GMP::__serialize GMP::\_\_serialize ================== (PHP 8 >= 8.1.0) GMP::\_\_serialize — Serializes the GMP object ### Description ``` public GMP::__serialize(): array ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php streamWrapper::dir_opendir streamWrapper::dir\_opendir =========================== (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::dir\_opendir — Open directory handle ### Description ``` public streamWrapper::dir_opendir(string $path, int $options): bool ``` This method is called in response to [opendir()](function.opendir). ### Parameters `path` Specifies the URL that was passed to [opendir()](function.opendir). > > **Note**: > > > The URL can be broken apart with [parse\_url()](function.parse-url). > > `options` ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [opendir()](function.opendir) - Open directory handle * [streamWrapper::dir\_closedir()](streamwrapper.dir-closedir) - Close directory handle * [parse\_url()](function.parse-url) - Parse a URL and return its components php Yaf_Loader::clearLocalNamespace Yaf\_Loader::clearLocalNamespace ================================ (Yaf >=1.0.0) Yaf\_Loader::clearLocalNamespace — The clearLocalNamespace purpose ### Description ``` public Yaf_Loader::clearLocalNamespace(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php lchown lchown ====== (PHP 5 >= 5.1.3, PHP 7, PHP 8) lchown — Changes user ownership of symlink ### Description ``` lchown(string $filename, string|int $user): bool ``` Attempts to change the owner of the symlink `filename` to user `user`. Only the superuser may change the owner of a symlink. ### Parameters `filename` Path to the file. `user` User name or number. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Changing the owner of a symbolic link** ``` <?php $target = 'output.php'; $link = 'output.html'; symlink($target, $link); lchown($link, 8); ?> ``` ### Notes > **Note**: This function will not work on [remote files](https://www.php.net/manual/en/features.remote-files.php) as the file to be examined must be accessible via the server's filesystem. > > > **Note**: This function is not implemented on Windows platforms. > > ### See Also * [chown()](function.chown) - Changes file owner * [lchgrp()](function.lchgrp) - Changes group ownership of symlink * [chgrp()](function.chgrp) - Changes file group * [chmod()](function.chmod) - Changes file mode
programming_docs
php EventBufferEvent::getOutput EventBufferEvent::getOutput =========================== (PECL event >= 1.2.6-beta) EventBufferEvent::getOutput — Returns underlying output buffer associated with current buffer event ### Description ``` public EventBufferEvent::getOutput(): EventBuffer ``` Returns underlying output buffer associated with current buffer event. An output buffer is a storage for data to be written. Note, there is also `[output](class.eventbufferevent#eventbufferevent.props.output)` property of [EventBufferEvent](class.eventbufferevent) class. ### Parameters This function has no parameters. ### Return Values Returns instance of [EventBuffer](class.eventbuffer) output buffer associated with current buffer event. ### Examples **Example #1 **EventBufferEvent::getOutput()** example** ``` <?php $base = new EventBase(); $dns_base = new EventDnsBase($base, TRUE); // Use async DNS resolving if (!$dns_base) {     exit("Failed to init DNS Base\n"); } $bev = new EventBufferEvent($base, /* use internal socket */ NULL,     EventBufferEvent::OPT_CLOSE_ON_FREE | EventBufferEvent::OPT_DEFER_CALLBACKS,     "readcb", /* writecb */ NULL, "eventcb", $base ); if (!$bev) {     exit("Failed creating bufferevent socket\n"); } $bev->enable(Event::READ | Event::WRITE); $output = $bev->getOutput(); if (!$output->add(     "GET {$argv[2]} HTTP/1.0\r\n".     "Host: {$argv[1]}\r\n".     "Connection: Close\r\n\r\n" )) {     exit("Failed adding request to output buffer\n"); } /* ... */ ?> ``` ### See Also * [EventBufferEvent::getInput()](eventbufferevent.getinput) - Returns underlying input buffer associated with current buffer event php sprintf sprintf ======= (PHP 4, PHP 5, PHP 7, PHP 8) sprintf — Return a formatted string ### Description ``` sprintf(string $format, mixed ...$values): string ``` Returns a string produced according to the formatting string `format`. ### Parameters `format` The format string is composed of zero or more directives: ordinary characters (excluding `%`) that are copied directly to the result and *conversion specifications*, each of which results in fetching its own parameter. A conversion specification follows this prototype: `%[argnum$][flags][width][.precision]specifier`. ##### Argnum An integer followed by a dollar sign `$`, to specify which number argument to treat in the conversion. **Flags**| Flag | Description | | --- | --- | | `-` | Left-justify within the given field width; Right justification is the default | | `+` | Prefix positive numbers with a plus sign `+`; Default only negative are prefixed with a negative sign. | | (space) | Pads the result with spaces. This is the default. | | `0` | Only left-pads numbers with zeros. With `s` specifiers this can also right-pad with zeros. | | `'`(char) | Pads the result with the character (char). | ##### Width An integer that says how many characters (minimum) this conversion should result in. ##### Precision A period `.` followed by an integer who's meaning depends on the specifier: * For `e`, `E`, `f` and `F` specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). * For `g`, `G`, `h` and `H` specifiers: this is the maximum number of significant digits to be printed. * For `s` specifier: it acts as a cutoff point, setting a maximum character limit to the string. > **Note**: If the period is specified without an explicit value for precision, 0 is assumed. > > > **Note**: Attempting to use a position specifier greater than **`PHP_INT_MAX`** will generate warnings. > > **Specifiers**| Specifier | Description | | --- | --- | | `%` | A literal percent character. No argument is required. | | `b` | The argument is treated as an integer and presented as a binary number. | | `c` | The argument is treated as an integer and presented as the character with that ASCII. | | `d` | The argument is treated as an integer and presented as a (signed) decimal number. | | `e` | The argument is treated as scientific notation (e.g. 1.2e+2). | | `E` | Like the `e` specifier but uses uppercase letter (e.g. 1.2E+2). | | `f` | The argument is treated as a float and presented as a floating-point number (locale aware). | | `F` | The argument is treated as a float and presented as a floating-point number (non-locale aware). | | `g` | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. | | `G` | Like the `g` specifier but uses `E` and `f`. | | `h` | Like the `g` specifier but uses `F`. Available as of PHP 8.0.0. | | `H` | Like the `g` specifier but uses `E` and `F`. Available as of PHP 8.0.0. | | `o` | The argument is treated as an integer and presented as an octal number. | | `s` | The argument is treated and presented as a string. | | `u` | The argument is treated as an integer and presented as an unsigned decimal number. | | `x` | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). | | `X` | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). | **Warning** The `c` type specifier ignores padding and width **Warning** Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results Variables will be co-erced to a suitable type for the specifier: **Type Handling**| Type | Specifiers | | --- | --- | | string | `s` | | int | `d`, `u`, `c`, `o`, `x`, `X`, `b` | | float | `e`, `E`, `f`, `F`, `g`, `G`, `h`, `H` | `values` ### Return Values Returns a string produced according to the formatting string `format`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function no longer returns **`false`** on failure. | ### Examples **Example #1 Argument swapping** The format string supports argument numbering/swapping. ``` <?php $num = 5; $location = 'tree'; $format = 'There are %d monkeys in the %s'; echo sprintf($format, $num, $location); ?> ``` The above example will output: ``` There are 5 monkeys in the tree ``` However imagine we are creating a format string in a separate file, commonly because we would like to internationalize it and we rewrite it as: ``` <?php $format = 'The %s contains %d monkeys'; echo sprintf($format, $num, $location); ?> ``` We now have a problem. The order of the placeholders in the format string does not match the order of the arguments in the code. We would like to leave the code as is and simply indicate in the format string which arguments the placeholders refer to. We would write the format string like this instead: ``` <?php $format = 'The %2$s contains %1$d monkeys'; echo sprintf($format, $num, $location); ?> ``` An added benefit is that placeholders can be repeated without adding more arguments in the code. ``` <?php $format = 'The %2$s contains %1$d monkeys.            That\'s a nice %2$s full of %1$d monkeys.'; echo sprintf($format, $num, $location); ?> ``` When using argument swapping, the `n$` *position specifier* must come immediately after the percent sign (`%`), before any other specifiers, as shown below. **Example #2 Specifying padding character** ``` <?php echo sprintf("%'.9d\n", 123); echo sprintf("%'.09d\n", 123); ?> ``` The above example will output: ``` ......123 000000123 ``` **Example #3 Position specifier with other specifiers** ``` <?php $format = 'The %2$s contains %1$04d monkeys'; echo sprintf($format, $num, $location); ?> ``` The above example will output: ``` The tree contains 0005 monkeys ``` **Example #4 **sprintf()**: zero-padded integers** ``` <?php $isodate = sprintf("%04d-%02d-%02d", $year, $month, $day); ?> ``` **Example #5 **sprintf()**: formatting currency** ``` <?php $money1 = 68.75; $money2 = 54.35; $money = $money1 + $money2; echo $money; echo "\n"; $formatted = sprintf("%01.2f", $money); echo $formatted; ?> ``` The above example will output: ``` 123.1 123.10 ``` **Example #6 **sprintf()**: scientific notation** ``` <?php $number = 362525200; echo sprintf("%.3e", $number); ?> ``` The above example will output: ``` 3.625e+8 ``` ### See Also * [printf()](function.printf) - Output a formatted string * [fprintf()](function.fprintf) - Write a formatted string to a stream * [vprintf()](function.vprintf) - Output a formatted string * [vsprintf()](function.vsprintf) - Return a formatted string * [vfprintf()](function.vfprintf) - Write a formatted string to a stream * [sscanf()](function.sscanf) - Parses input from a string according to a format * [fscanf()](function.fscanf) - Parses input from a file according to a format * [number\_format()](function.number-format) - Format a number with grouped thousands * [date()](function.date) - Format a Unix timestamp php Imagick::solarizeImage Imagick::solarizeImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::solarizeImage — Applies a solarizing effect to the image ### Description ``` public Imagick::solarizeImage(int $threshold): bool ``` Applies a special effect to the image, similar to the effect achieved in a photo darkroom by selectively exposing areas of photo sensitive paper to light. Threshold ranges from 0 to QuantumRange and is a measure of the extent of the solarization. ### Parameters `threshold` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::solarizeImage()**** ``` <?php function solarizeImage($imagePath, $solarizeThreshold) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->solarizeImage($solarizeThreshold * \Imagick::getQuantum());     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php getrusage getrusage ========= (PHP 4, PHP 5, PHP 7, PHP 8) getrusage — Gets the current resource usages ### Description ``` getrusage(int $mode = 0): array|false ``` This is an interface to **getrusage(2)**. It gets data returned from the system call. ### Parameters `mode` If `mode` is 1, getrusage will be called with **`RUSAGE_CHILDREN`**. ### Return Values Returns an associative array containing the data returned from the system call. All entries are accessible by using their documented field names. Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.0.0 | This function is now supported on Windows. | ### Examples **Example #1 **getrusage()** example** ``` <?php $dat = getrusage(); echo $dat["ru_oublock"];       // number of block output operations echo $dat["ru_inblock"];       // number of block input operations echo $dat["ru_msgsnd"];        // number of IPC messages sent echo $dat["ru_msgrcv"];        // number of IPC messages received echo $dat["ru_maxrss"];        // maximum resident set size echo $dat["ru_ixrss"];         // integral shared memory size echo $dat["ru_idrss"];         // integral unshared data size echo $dat["ru_minflt"];        // number of page reclaims (soft page faults) echo $dat["ru_majflt"];        // number of page faults (hard page faults) echo $dat["ru_nsignals"];      // number of signals received echo $dat["ru_nvcsw"];         // number of voluntary context switches echo $dat["ru_nivcsw"];        // number of involuntary context switches echo $dat["ru_nswap"];         // number of swaps echo $dat["ru_utime.tv_usec"]; // user time used (microseconds) echo $dat["ru_utime.tv_sec"];  // user time used (seconds) echo $dat["ru_stime.tv_usec"]; // system time used (microseconds) ?> ``` ### Notes > > **Note**: > > > On Windows **getrusage()** will only return the following members: > > > * `"ru_stime.tv_sec"` > * `"ru_stime.tv_usec"` > * `"ru_utime.tv_sec"` > * `"ru_utime.tv_usec"` > * `"ru_majflt"` (only if `mode` is **`RUSAGE_SELF`**) > * `"ru_maxrss"` (only if `mode` is **`RUSAGE_SELF`**) > > If **getrusage()** is called with `mode` set to `1` (**`RUSAGE_CHILDREN`**), then resource usage for threads are collected (meaning that internally the function is called with **`RUSAGE_THREAD`**). > > > > **Note**: > > > on BeOS 2000, only the following members are returned: > > > * `"ru_stime.tv_sec"` > * `"ru_stime.tv_usec"` > * `"ru_utime.tv_sec"` > * `"ru_utime.tv_usec"` > > ### See Also * Your system's man page on **getrusage(2)** php SplFixedArray::__construct SplFixedArray::\_\_construct ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplFixedArray::\_\_construct — Constructs a new fixed array ### Description public **SplFixedArray::\_\_construct**(int `$size` = 0) Initializes a fixed array with a number of **`null`** values equal to `size`. ### Parameters `size` The size of the fixed array. This expects a number between `0` and **`PHP_INT_MAX`**. ### Errors/Exceptions Throws a [ValueError](class.valueerror) when `size` is a negative integer. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Now throws a [ValueError](class.valueerror) if `size` is a negative; previously it threw a [InvalidArgumentException](class.invalidargumentexception). | ### Examples **Example #1 **SplFixedArray::\_\_construct()** example** ``` <?php $array = new SplFixedArray(5); $array[1] = 2; $array[4] = "foo"; foreach($array as $v) {   var_dump($v); } ?> ``` The above example will output: ``` NULL int(2) NULL NULL string(3) "foo" ``` php The PDOException class The PDOException class ====================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Represents an error raised by PDO. You should not throw a **PDOException** from your own code. See [Exceptions](language.exceptions) for more information about Exceptions in PHP. Class synopsis -------------- class **PDOException** extends [RuntimeException](class.runtimeexception) { /\* Properties \*/ protected int|string [$code](class.pdoexception#pdoexception.props.code); public ?array [$errorInfo](class.pdoexception#pdoexception.props.errorinfo) = null; /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } Properties ---------- errorInfo Corresponds to [PDO::errorInfo()](pdo.errorinfo) or [PDOStatement::errorInfo()](pdostatement.errorinfo) code `SQLSTATE` error code. Use [Exception::getCode()](exception.getcode) to access it. php ArgumentCountError ArgumentCountError ================== Introduction ------------ (PHP 7 >= PHP 7.1.0, PHP 8) **ArgumentCountError** is thrown when too few arguments are passed to a user-defined function or method. Class synopsis -------------- class **ArgumentCountError** extends [TypeError](class.typeerror) { /\* Inherited properties \*/ protected string [$message](class.error#error.props.message) = ""; private string [$string](class.error#error.props.string) = ""; protected int [$code](class.error#error.props.code); protected string [$file](class.error#error.props.file) = ""; protected int [$line](class.error#error.props.line); private array [$trace](class.error#error.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.error#error.props.previous) = null; /\* Inherited methods \*/ ``` final public Error::getMessage(): string ``` ``` final public Error::getPrevious(): ?Throwable ``` ``` final public Error::getCode(): int ``` ``` final public Error::getFile(): string ``` ``` final public Error::getLine(): int ``` ``` final public Error::getTrace(): array ``` ``` final public Error::getTraceAsString(): string ``` ``` public Error::__toString(): string ``` ``` private Error::__clone(): void ``` } php NumberFormatter::format NumberFormatter::format ======================= numfmt\_format ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::format -- numfmt\_format — Format a number ### Description Object-oriented style ``` public NumberFormatter::format(int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false ``` Procedural style ``` numfmt_format(NumberFormatter $formatter, int|float $num, int $type = NumberFormatter::TYPE_DEFAULT): string|false ``` Format a numeric value according to the formatter rules. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `num` The value to format. Can be int or float, other values will be converted to a numeric value. `type` The [formatting type](class.numberformatter#intl.numberformatter-constants.types) to use. Note that **`NumberFormatter::TYPE_CURRENCY`** is not supported; use [NumberFormatter::formatCurrency()](numberformatter.formatcurrency) instead. ### Return Values Returns the string containing formatted value, or **`false`** on error. ### Examples **Example #1 **numfmt\_format()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); $data = numfmt_format($fmt, 1234567.891234567890000); if(intl_is_failure(numfmt_format($fmt))) {     report_error("Formatter error"); } ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); $fmt->format(1234567.891234567890000); if(intl_is_failure($fmt->getErrorCode())) {     report_error("Formatter error"); } ?> ``` The above example will output: ``` 1.234.567,891 ``` ### Notes > > **Note**: > > > Formats achievable by this method of formatting cannot fully use the possibilities of underlying ICU library, such as to format currency with narrow currency symbol. > > To fully utilize them use [msgfmt\_format\_message()](messageformatter.formatmessage). > > ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_format\_currency()](numberformatter.formatcurrency) - Format a currency value * [numfmt\_parse()](numberformatter.parse) - Parse a number * [msgfmt\_format\_message()](messageformatter.formatmessage) - Quick format message php SplFileInfo::__construct SplFileInfo::\_\_construct ========================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::\_\_construct — Construct a new SplFileInfo object ### Description public **SplFileInfo::\_\_construct**(string `$filename`) Creates a new SplFileInfo object for the file\_name specified. The file does not need to exist, or be readable. ### Parameters `filename` Path to the file. ### Examples **Example #1 **SplFileInfo::\_\_construct()** example** ``` <?php $info = new SplFileInfo('example.php'); if ($info->isFile()) {     echo $info->getRealPath(); } ?> ```
programming_docs
php Parle\RLexer::consume Parle\RLexer::consume ===================== (PECL parle >= 0.5.1) Parle\RLexer::consume — Pass the data for processing ### Description ``` public Parle\RLexer::consume(string $data): void ``` Consume the data for lexing. ### Parameters `data` Data to be lexed. ### Return Values No value is returned. php pg_query_params pg\_query\_params ================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) pg\_query\_params — Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text ### Description ``` pg_query_params(PgSql\Connection $connection = ?, string $query, array $params): PgSql\Result|false ``` Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text. **pg\_query\_params()** is like [pg\_query()](function.pg-query), but offers additional functionality: parameter values can be specified separately from the command string proper. **pg\_query\_params()** is supported only against PostgreSQL 7.4 or higher connections; it will fail when using earlier versions. If parameters are used, they are referred to in the `query` string as $1, $2, etc. The same parameter may appear more than once in the `query`; the same value will be used in that case. `params` specifies the actual values of the parameters. A **`null`** value in this array means the corresponding parameter is SQL `NULL`. The primary advantage of **pg\_query\_params()** over [pg\_query()](function.pg-query) is that parameter values may be separated from the `query` string, thus avoiding the need for tedious and error-prone quoting and escaping. Unlike [pg\_query()](function.pg-query), **pg\_query\_params()** allows at most one SQL command in the given string. (There can be semicolons in it, but not more than one nonempty command.) ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `query` The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc. User-supplied values should always be passed as parameters, not interpolated into the query string, where they form possible [SQL injection](https://www.php.net/manual/en/security.database.sql-injection.php) attack vectors and introduce bugs when handling data containing quotes. If for some reason you cannot use a parameter, ensure that interpolated values are [properly escaped](function.pg-escape-string). `params` An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders. Values intended for `bytea` fields are not supported as parameters. Use [pg\_escape\_bytea()](function.pg-escape-bytea) instead, or use the large object functions. ### Return Values An [PgSql\Result](class.pgsql-result) instance on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Returns an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Using **pg\_query\_params()**** ``` <?php // Connect to a database named "mary" $dbconn = pg_connect("dbname=mary"); // Find all shops named Joe's Widgets.  Note that it is not necessary to // escape "Joe's Widgets" $result = pg_query_params($dbconn, 'SELECT * FROM shops WHERE name = $1', array("Joe's Widgets")); // Compare against just using pg_query $str = pg_escape_string("Joe's Widgets"); $result = pg_query($dbconn, "SELECT * FROM shops WHERE name = '{$str}'"); ?> ``` ### See Also * [pg\_query()](function.pg-query) - Execute a query php debug_backtrace debug\_backtrace ================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) debug\_backtrace — Generates a backtrace ### Description ``` debug_backtrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT, int $limit = 0): array ``` **debug\_backtrace()** generates a PHP backtrace. ### Parameters `options` This parameter is a bitmask for the following options: ****debug\_backtrace()** options**| DEBUG\_BACKTRACE\_PROVIDE\_OBJECT | Whether or not to populate the "object" index. | | DEBUG\_BACKTRACE\_IGNORE\_ARGS | Whether or not to omit the "args" index, and thus all the function/method arguments, to save memory. | `limit` This parameter can be used to limit the number of stack frames returned. By default (`limit`=`0`) it returns all stack frames. ### Return Values Returns an array of associative arrays. The possible returned elements are as follows: **Possible returned elements from **debug\_backtrace()****| Name | Type | Description | | --- | --- | --- | | function | string | The current function name. See also [\_\_FUNCTION\_\_](language.constants.predefined). | | line | int | The current line number. See also [\_\_LINE\_\_](language.constants.predefined). | | file | string | The current file name. See also [\_\_FILE\_\_](language.constants.predefined). | | class | string | The current [class](https://www.php.net/manual/en/language.oop5.php) name. See also [\_\_CLASS\_\_](language.constants.predefined) | | object | object | The current [object](https://www.php.net/manual/en/language.oop5.php). | | type | string | The current call type. If a method call, "->" is returned. If a static method call, "::" is returned. If a function call, nothing is returned. | | args | array | If inside a function, this lists the functions arguments. If inside an included file, this lists the included file name(s). | ### Examples **Example #1 **debug\_backtrace()** example** ``` <?php // filename: /tmp/a.php function a_test($str) {     echo "\nHi: $str";     var_dump(debug_backtrace()); } a_test('friend'); ?> <?php // filename: /tmp/b.php include_once '/tmp/a.php'; ?> ``` Results similar to the following when executing /tmp/b.php: ``` Hi: friend array(2) { [0]=> array(4) { ["file"] => string(10) "/tmp/a.php" ["line"] => int(10) ["function"] => string(6) "a_test" ["args"]=> array(1) { [0] => &string(6) "friend" } } [1]=> array(4) { ["file"] => string(10) "/tmp/b.php" ["line"] => int(2) ["args"] => array(1) { [0] => string(10) "/tmp/a.php" } ["function"] => string(12) "include_once" } } ``` ### See Also * [trigger\_error()](function.trigger-error) - Generates a user-level error/warning/notice message * [debug\_print\_backtrace()](function.debug-print-backtrace) - Prints a backtrace php password_needs_rehash password\_needs\_rehash ======================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) password\_needs\_rehash — Checks if the given hash matches the given options ### Description ``` password_needs_rehash(string $hash, string|int|null $algo, array $options = []): bool ``` This function checks to see if the supplied hash implements the algorithm and options provided. If not, it is assumed that the hash needs to be rehashed. ### Parameters `hash` A hash created by [password\_hash()](function.password-hash). `algo` A [password algorithm constant](https://www.php.net/manual/en/password.constants.php) denoting the algorithm to use when hashing the password. `options` An associative array containing options. See the [password algorithm constants](https://www.php.net/manual/en/password.constants.php) for documentation on the supported options for each algorithm. ### Return Values Returns **`true`** if the hash should be rehashed to match the given `algo` and `options`, or **`false`** otherwise. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | The `algo` parameter expects a string now, but still accepts ints for backward compatibility. | ### Examples **Example #1 Usage of **password\_needs\_rehash()**** ``` <?php $password = 'rasmuslerdorf'; $hash = '$2y$10$YCFsG6elYca568hBi2pZ0.3LDL5wjgxct1N8w/oLR/jfHsiQwCqTS'; // The cost parameter can change over time as hardware improves $options = array('cost' => 11); // Verify stored hash against plain-text password if (password_verify($password, $hash)) {     // Check if a newer hashing algorithm is available     // or the cost has changed     if (password_needs_rehash($hash, PASSWORD_DEFAULT, $options)) {         // If so, create a new hash, and replace the old one         $newHash = password_hash($password, PASSWORD_DEFAULT, $options);     }     // Log user in } ?> ``` php The mysqli class The mysqli class ================ Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents a connection between PHP and a MySQL database. Class synopsis -------------- class **mysqli** { /\* Properties \*/ public readonly int|string [$affected\_rows](mysqli.affected-rows); public readonly string [$client\_info](mysqli.get-client-info); public readonly int [$client\_version](mysqli.get-client-version); public readonly int [$connect\_errno](mysqli.connect-errno); public readonly ?string [$connect\_error](mysqli.connect-error); public readonly int [$errno](mysqli.errno); public readonly string [$error](mysqli.error); public readonly array [$error\_list](mysqli.error-list); public readonly int [$field\_count](mysqli.field-count); public readonly string [$host\_info](mysqli.get-host-info); public readonly ?string [$info](mysqli.info); public readonly int|string [$insert\_id](mysqli.insert-id); public readonly string [$server\_info](mysqli.get-server-info); public readonly int [$server\_version](mysqli.get-server-version); public readonly string [$sqlstate](mysqli.sqlstate); public readonly int [$protocol\_version](mysqli.get-proto-info); public readonly int [$thread\_id](mysqli.thread-id); public readonly int [$warning\_count](mysqli.warning-count); /\* Methods \*/ public [\_\_construct](mysqli.construct)( string `$hostname` = ini\_get("mysqli.default\_host"), string `$username` = ini\_get("mysqli.default\_user"), string `$password` = ini\_get("mysqli.default\_pw"), string `$database` = "", int `$port` = ini\_get("mysqli.default\_port"), string `$socket` = ini\_get("mysqli.default\_socket") ) ``` public autocommit(bool $enable): bool ``` ``` public begin_transaction(int $flags = 0, ?string $name = null): bool ``` ``` public change_user(string $username, string $password, ?string $database): bool ``` ``` public character_set_name(): string ``` ``` public close(): bool ``` ``` public commit(int $flags = 0, ?string $name = null): bool ``` ``` public connect( string $hostname = ini_get("mysqli.default_host"), string $username = ini_get("mysqli.default_user"), string $password = ini_get("mysqli.default_pw"), string $database = "", int $port = ini_get("mysqli.default_port"), string $socket = ini_get("mysqli.default_socket") ): void ``` ``` public debug(string $options): bool ``` ``` public dump_debug_info(): bool ``` ``` public execute_query(string $query, ?array $params = null): mysqli_result|bool ``` ``` public get_charset(): ?object ``` ``` public get_client_info(): string ``` ``` public get_connection_stats(): array ``` ``` public get_server_info(): string ``` ``` public get_warnings(): mysqli_warning|false ``` ``` public init(): ?bool ``` ``` public kill(int $process_id): bool ``` ``` public more_results(): bool ``` ``` public multi_query(string $query): bool ``` ``` public next_result(): bool ``` ``` public options(int $option, string|int $value): bool ``` ``` public ping(): bool ``` ``` public static poll( ?array &$read, ?array &$error, array &$reject, int $seconds, int $microseconds = 0 ): int|false ``` ``` public prepare(string $query): mysqli_stmt|false ``` ``` public query(string $query, int $result_mode = MYSQLI_STORE_RESULT): mysqli_result|bool ``` ``` public real_connect( string $host = ?, string $username = ?, string $passwd = ?, string $dbname = ?, int $port = ?, string $socket = ?, int $flags = ? ): bool ``` ``` public real_escape_string(string $string): string ``` ``` public real_query(string $query): bool ``` ``` public reap_async_query(): mysqli_result|bool ``` ``` public refresh(int $flags): bool ``` ``` public release_savepoint(string $name): bool ``` ``` public rollback(int $flags = 0, ?string $name = null): bool ``` ``` public savepoint(string $name): bool ``` ``` public select_db(string $database): bool ``` ``` public set_charset(string $charset): bool ``` ``` public ssl_set( ?string $key, ?string $certificate, ?string $ca_certificate, ?string $ca_path, ?string $cipher_algos ): bool ``` ``` public stat(): string|false ``` ``` public stmt_init(): mysqli_stmt|false ``` ``` public store_result(int $mode = 0): mysqli_result|false ``` ``` public thread_safe(): bool ``` ``` public use_result(): mysqli_result|false ``` } Table of Contents ----------------- * [mysqli::$affected\_rows](mysqli.affected-rows) — Gets the number of affected rows in a previous MySQL operation * [mysqli::autocommit](mysqli.autocommit) — Turns on or off auto-committing database modifications * [mysqli::begin\_transaction](mysqli.begin-transaction) — Starts a transaction * [mysqli::change\_user](mysqli.change-user) — Changes the user of the specified database connection * [mysqli::character\_set\_name](mysqli.character-set-name) — Returns the current character set of the database connection * [mysqli::close](mysqli.close) — Closes a previously opened database connection * [mysqli::commit](mysqli.commit) — Commits the current transaction * [mysqli::$connect\_errno](mysqli.connect-errno) — Returns the error code from last connect call * [mysqli::$connect\_error](mysqli.connect-error) — Returns a description of the last connection error * [mysqli::\_\_construct](mysqli.construct) — Open a new connection to the MySQL server * [mysqli::debug](mysqli.debug) — Performs debugging operations * [mysqli::dump\_debug\_info](mysqli.dump-debug-info) — Dump debugging information into the log * [mysqli::$errno](mysqli.errno) — Returns the error code for the most recent function call * [mysqli::$error\_list](mysqli.error-list) — Returns a list of errors from the last command executed * [mysqli::$error](mysqli.error) — Returns a string description of the last error * [mysqli::execute\_query](mysqli.execute-query) — Prepares, binds parameters, and executes SQL statement * [mysqli::$field\_count](mysqli.field-count) — Returns the number of columns for the most recent query * [mysqli::get\_charset](mysqli.get-charset) — Returns a character set object * [mysqli::$client\_info](mysqli.get-client-info) — Get MySQL client info * [mysqli::$client\_version](mysqli.get-client-version) — Returns the MySQL client version as an integer * [mysqli::get\_connection\_stats](mysqli.get-connection-stats) — Returns statistics about the client connection * [mysqli::$host\_info](mysqli.get-host-info) — Returns a string representing the type of connection used * [mysqli::$protocol\_version](mysqli.get-proto-info) — Returns the version of the MySQL protocol used * [mysqli::$server\_info](mysqli.get-server-info) — Returns the version of the MySQL server * [mysqli::$server\_version](mysqli.get-server-version) — Returns the version of the MySQL server as an integer * [mysqli::get\_warnings](mysqli.get-warnings) — Get result of SHOW WARNINGS * [mysqli::$info](mysqli.info) — Retrieves information about the most recently executed query * [mysqli::init](mysqli.init) — Initializes MySQLi and returns an object for use with mysqli\_real\_connect() * [mysqli::$insert\_id](mysqli.insert-id) — Returns the value generated for an AUTO\_INCREMENT column by the last query * [mysqli::kill](mysqli.kill) — Asks the server to kill a MySQL thread * [mysqli::more\_results](mysqli.more-results) — Check if there are any more query results from a multi query * [mysqli::multi\_query](mysqli.multi-query) — Performs one or more queries on the database * [mysqli::next\_result](mysqli.next-result) — Prepare next result from multi\_query * [mysqli::options](mysqli.options) — Set options * [mysqli::ping](mysqli.ping) — Pings a server connection, or tries to reconnect if the connection has gone down * [mysqli::poll](mysqli.poll) — Poll connections * [mysqli::prepare](mysqli.prepare) — Prepares an SQL statement for execution * [mysqli::query](mysqli.query) — Performs a query on the database * [mysqli::real\_connect](mysqli.real-connect) — Opens a connection to a mysql server * [mysqli::real\_escape\_string](mysqli.real-escape-string) — Escapes special characters in a string for use in an SQL statement, taking into account the current charset of the connection * [mysqli::real\_query](mysqli.real-query) — Execute an SQL query * [mysqli::reap\_async\_query](mysqli.reap-async-query) — Get result from async query * [mysqli::refresh](mysqli.refresh) — Refreshes * [mysqli::release\_savepoint](mysqli.release-savepoint) — Removes the named savepoint from the set of savepoints of the current transaction * [mysqli::rollback](mysqli.rollback) — Rolls back current transaction * [mysqli::savepoint](mysqli.savepoint) — Set a named transaction savepoint * [mysqli::select\_db](mysqli.select-db) — Selects the default database for database queries * [mysqli::set\_charset](mysqli.set-charset) — Sets the client character set * [mysqli::$sqlstate](mysqli.sqlstate) — Returns the SQLSTATE error from previous MySQL operation * [mysqli::ssl\_set](mysqli.ssl-set) — Used for establishing secure connections using SSL * [mysqli::stat](mysqli.stat) — Gets the current system status * [mysqli::stmt\_init](mysqli.stmt-init) — Initializes a statement and returns an object for use with mysqli\_stmt\_prepare * [mysqli::store\_result](mysqli.store-result) — Transfers a result set from the last query * [mysqli::$thread\_id](mysqli.thread-id) — Returns the thread ID for the current connection * [mysqli::thread\_safe](mysqli.thread-safe) — Returns whether thread safety is given or not * [mysqli::use\_result](mysqli.use-result) — Initiate a result set retrieval * [mysqli::$warning\_count](mysqli.warning-count) — Returns the number of warnings from the last query for the given link php The Yaf_Controller_Abstract class The Yaf\_Controller\_Abstract class =================================== Introduction ------------ (Yaf >=1.0.0) **Yaf\_Controller\_Abstract** is the heart of Yaf's system. MVC stands for Model-View-Controller and is a design pattern targeted at separating application logic from display logic. Every custom controller shall inherit **Yaf\_Controller\_Abstract**. You will find that you can not define \_\_construct function for your custom controller, thus, **Yaf\_Controller\_Abstract** provides a magic method: [Yaf\_Controller\_Abstract::init()](yaf-controller-abstract.init). If you have defined a init() method in your custom controller, it will be called as long as the controller was instantiated. Action may have arguments, when a request coming, if there are the same name variable in the request parameters(see [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam)) after routed, Yaf will pass them to the action method (see [Yaf\_Action\_Abstract::execute()](yaf-action-abstract.execute)). > > **Note**: > > > These arguments are directly fetched without filtering, it should be carefully processed before use them. > > Class synopsis -------------- abstract class **Yaf\_Controller\_Abstract** { /\* Properties \*/ public [$actions](class.yaf-controller-abstract#yaf-controller-abstract.props.actions); protected [$\_module](class.yaf-controller-abstract#yaf-controller-abstract.props.module); protected [$\_name](class.yaf-controller-abstract#yaf-controller-abstract.props.name); protected [$\_request](class.yaf-controller-abstract#yaf-controller-abstract.props.request); protected [$\_response](class.yaf-controller-abstract#yaf-controller-abstract.props.response); protected [$\_invoke\_args](class.yaf-controller-abstract#yaf-controller-abstract.props.invoke-args); protected [$\_view](class.yaf-controller-abstract#yaf-controller-abstract.props.view); /\* Methods \*/ final private [\_\_construct](yaf-controller-abstract.construct)() ``` protected display(string $tpl, array $parameters = ?): bool ``` ``` public forward(string $action, array $paramters = ?): bool ``` ``` public getInvokeArg(string $name): void ``` ``` public getInvokeArgs(): void ``` ``` public getModuleName(): string ``` ``` public getName(): string ``` ``` public getRequest(): Yaf_Request_Abstract ``` ``` public getResponse(): Yaf_Response_Abstract ``` ``` public getView(): Yaf_View_Interface ``` ``` public getViewpath(): string ``` ``` public init(): void ``` ``` public initView(array $options = ?): void ``` ``` public redirect(string $url): bool ``` ``` protected render(string $tpl, array $parameters = ?): string ``` ``` public setViewpath(string $view_directory): void ``` } Properties ---------- actions You can also define an action method in a separate PHP script by using this property and [Yaf\_Action\_Abstract](class.yaf-action-abstract). **Example #1 define action in a separate file** ``` <?php class IndexController extends Yaf_Controller_Abstract {     protected $actions = array(         /** now dummyAction is defined in a separate file */         "dummy" => "actions/Dummy_action.php",     );     /* action method may have arguments */     public function indexAction($name, $id) {        /* $name and $id are unsafe raw data */        assert($name == $this->getRequest()->getParam("name"));        assert($id   == $this->_request->getParam("id"));     } } ?> ``` **Example #2 Dummy\_action.php** ``` <?php class DummyAction extends Yaf_Action_Abstract {     /* an action class shall define this method as the entry point */     public function execute() {     } } ?> ``` \_module module name \_name controller name \_request current request object \_response current response object \_invoke\_args \_view view engine object Table of Contents ----------------- * [Yaf\_Controller\_Abstract::\_\_construct](yaf-controller-abstract.construct) — Yaf\_Controller\_Abstract constructor * [Yaf\_Controller\_Abstract::display](yaf-controller-abstract.display) — The display purpose * [Yaf\_Controller\_Abstract::forward](yaf-controller-abstract.forward) — Forward to another action * [Yaf\_Controller\_Abstract::getInvokeArg](yaf-controller-abstract.getinvokearg) — The getInvokeArg purpose * [Yaf\_Controller\_Abstract::getInvokeArgs](yaf-controller-abstract.getinvokeargs) — The getInvokeArgs purpose * [Yaf\_Controller\_Abstract::getModuleName](yaf-controller-abstract.getmodulename) — Get module name * [Yaf\_Controller\_Abstract::getName](yaf-controller-abstract.getname) — Get self name * [Yaf\_Controller\_Abstract::getRequest](yaf-controller-abstract.getrequest) — Retrieve current request object * [Yaf\_Controller\_Abstract::getResponse](yaf-controller-abstract.getresponse) — Retrieve current response object * [Yaf\_Controller\_Abstract::getView](yaf-controller-abstract.getview) — Retrieve the view engine * [Yaf\_Controller\_Abstract::getViewpath](yaf-controller-abstract.getviewpath) — The getViewpath purpose * [Yaf\_Controller\_Abstract::init](yaf-controller-abstract.init) — Controller initializer * [Yaf\_Controller\_Abstract::initView](yaf-controller-abstract.initview) — The initView purpose * [Yaf\_Controller\_Abstract::redirect](yaf-controller-abstract.redirect) — Redirect to a URL * [Yaf\_Controller\_Abstract::render](yaf-controller-abstract.render) — Render view template * [Yaf\_Controller\_Abstract::setViewpath](yaf-controller-abstract.setviewpath) — The setViewpath purpose
programming_docs
php The DOMProcessingInstruction class The DOMProcessingInstruction class ================================== Class synopsis -------------- (PHP 5, PHP 7, PHP 8) class **DOMProcessingInstruction** extends [DOMNode](class.domnode) { /\* Properties \*/ public readonly string [$target](class.domprocessinginstruction#domprocessinginstruction.props.target); public string [$data](class.domprocessinginstruction#domprocessinginstruction.props.data); /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domprocessinginstruction.construct)(string `$name`, string `$value` = "") /\* Inherited methods \*/ ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- target data Table of Contents ----------------- * [DOMProcessingInstruction::\_\_construct](domprocessinginstruction.construct) — Creates a new DOMProcessingInstruction object php DOMParentNode::append DOMParentNode::append ===================== (PHP 8) DOMParentNode::append — Appends nodes after the last child node ### Description ``` public DOMParentNode::append(DOMNode|string ...$nodes): void ``` Appends one or many `nodes` to the list of children after the last child node. ### Parameters `nodes` The nodes to append. ### Return Values No value is returned. ### See Also * [DOMParentNode::prepend()](domparentnode.prepend) - Prepends nodes before the first child node php SolrQuery::setTermsMaxCount SolrQuery::setTermsMaxCount =========================== (PECL solr >= 0.9.2) SolrQuery::setTermsMaxCount — Sets the maximum document frequency ### Description ``` public SolrQuery::setTermsMaxCount(int $frequency): SolrQuery ``` Sets the maximum document frequency. ### Parameters `frequency` The maximum document frequency. ### Return Values Returns the current SolrQuery object, if the return value is used. php Componere\Definition::isRegistered Componere\Definition::isRegistered ================================== (Componere 2 >= 2.1.0) Componere\Definition::isRegistered — State Detection ### Description ``` public Componere\Definition::isRegistered(): bool ``` Shall detect the registration state of this Definition ### Return Values Shall return true if this Definition is registered php Phar::copy Phar::copy ========== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::copy — Copy a file internal to the phar archive to another new file within the phar ### Description ``` public Phar::copy(string $from, string $to): bool ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > Copy a file internal to the phar archive to another new file within the phar. This is an object-oriented alternative to using [copy()](function.copy) with the phar stream wrapper. ### Parameters `from` `to` ### Return Values returns **`true`** on success, but it is safer to encase method call in a try/catch block and assume success if no exception is thrown. ### Errors/Exceptions throws [UnexpectedValueException](class.unexpectedvalueexception) if the source file does not exist, the destination file already exists, write access is disabled, opening either file fails, reading the source file fails, or a [PharException](class.pharexception) if writing the changes to the phar fails. ### Examples **Example #1 A **Phar::copy()** example** This example shows using **Phar::copy()** and the equivalent stream wrapper performance of the same thing. The primary difference between the two approaches is error handling. All Phar methods throw exceptions, whereas the stream wrapper uses [trigger\_error()](function.trigger-error). ``` <?php try {     $phar = new Phar('myphar.phar');     $phar['a'] = 'hi';     $phar->copy('a', 'b');     echo $phar['b']; // outputs "hi" } catch (Exception $e) {     // handle error } // the stream wrapper equivalent of the above code. // E_WARNINGS are triggered on error rather than exceptions. copy('phar://myphar.phar/a', 'phar//myphar.phar/c'); echo file_get_contents('phar://myphar.phar/c'); // outputs "hi" ?> ``` php The EvChild class The EvChild class ================= Introduction ------------ (PECL ev >= 0.2.0) **EvChild** watchers trigger when the process receives a **`SIGCHLD`** in response to some child status changes (most typically when a child dies or exits). It is permissible to install an **`EvChild`** watcher after the child has been forked(which implies it might have already exited), as long as the event loop isn't entered(or is continued from a watcher), i.e. forking and then immediately registering a watcher for the child is fine, but forking and registering a watcher a few event loop iterations later or in the next callback invocation is not. It is allowed to register **EvChild** watchers in the *default loop* only. Class synopsis -------------- class **EvChild** extends [EvWatcher](class.evwatcher) { /\* Properties \*/ public [$pid](class.evchild#evchild.props.pid); public [$rpid](class.evchild#evchild.props.rpid); public [$rstatus](class.evchild#evchild.props.rstatus); /\* Inherited properties \*/ public [$is\_active](class.evwatcher#evwatcher.props.is-active); public [$data](class.evwatcher#evwatcher.props.data); public [$is\_pending](class.evwatcher#evwatcher.props.is-pending); public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evchild.construct)( int `$pid` , bool `$trace` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** , int `$priority` = 0 ) ``` final public static createStopped( int $pid , bool $trace , callable $callback , mixed $data = ?, int $priority = ? ): object ``` ``` public set( int $pid , bool $trace ): void ``` /\* Inherited methods \*/ ``` public EvWatcher::clear(): int ``` ``` public EvWatcher::feed( int $revents ): void ``` ``` public EvWatcher::getLoop(): EvLoop ``` ``` public EvWatcher::invoke( int $revents ): void ``` ``` public EvWatcher::keepalive( bool $value = ?): bool ``` ``` public EvWatcher::setCallback( callable $callback ): void ``` ``` public EvWatcher::start(): void ``` ``` public EvWatcher::stop(): void ``` } Properties ---------- pid *Readonly* . The process ID this watcher watches out for, or **`0`** , meaning any process ID. rpid *Readonly* .The process ID that detected a status change. rstatus *Readonly* . The process exit status caused by rpid . Table of Contents ----------------- * [EvChild::\_\_construct](evchild.construct) — Constructs the EvChild watcher object * [EvChild::createStopped](evchild.createstopped) — Create instance of a stopped EvCheck watcher * [EvChild::set](evchild.set) — Configures the watcher php Gmagick::getimageprofile Gmagick::getimageprofile ======================== (PECL gmagick >= Unknown) Gmagick::getimageprofile — Returns the named image profile ### Description ``` public Gmagick::getimageprofile(string $name): string ``` Returns the named image profile. ### Parameters This function has no parameters. ### Return Values Returns a string containing the image profile. ### Errors/Exceptions Throws an **GmagickException** on error. php uopz_set_property uopz\_set\_property =================== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_set\_property — Sets value of existing class or instance property ### Description ``` uopz_set_property(string $class, string $property, mixed $value): void ``` ``` uopz_set_property(object $instance, string $property, mixed $value): void ``` Sets the value of an existing static class property, if `class` is given, or the value of an instance property (regardless whether the instance property already exists), if `instance` is given. ### Parameters `class` The name of the class. `instance` The object instance. `property` The name of the property. `value` The value to assign to the property. ### Return Values No value is returned. ### Examples **Example #1 Basic **uopz\_set\_property()** Usage** ``` <?php class Foo {    private static $staticBar;    private $bar;    public static function testStaticBar() {       return self::$staticBar;    }    public function testBar() {       return $this->bar;    } } $foo = new Foo; uopz_set_property('Foo', 'staticBar', 10); uopz_set_property($foo, 'bar', 100); var_dump(Foo::testStaticBar()); var_dump($foo->testBar()); ?> ``` The above example will output: ``` int(10) ``` ### See Also * [uopz\_get\_property()](function.uopz-get-property) - Gets value of class or instance property php The DeflateContext class The DeflateContext class ======================== Introduction ------------ (PHP 8) A fully opaque class which replaces `zlib.deflate` resources as of PHP 8.0.0. Class synopsis -------------- final class **DeflateContext** { /\* Methods \*/ public [\_\_construct](deflatecontext.construct)() } Table of Contents ----------------- * [DeflateContext::\_\_construct](deflatecontext.construct) — Construct a new DeflateContext instance php imagegetinterpolation imagegetinterpolation ===================== (PHP 8) imagegetinterpolation — Get the interpolation method ### Description ``` imagegetinterpolation(GdImage $image): int ``` Gets the currently set interpolation method of the `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). ### Return Values Returns the interpolation method. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### See Also * [imagesetinterpolation()](function.imagesetinterpolation) - Set the interpolation method php Componere\Definition::addProperty Componere\Definition::addProperty ================================= (Componere 2 >= 2.1.0) Componere\Definition::addProperty — Add Property ### Description ``` public Componere\Definition::addProperty(string $name, Componere\Value $value): Definition ``` Shall declare a class property on the current Definition ### Parameters `name` The case sensitive name for the property `value` The default Value for the property ### Return Values The current Definition ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if Definition was registered **Warning** Shall throw [RuntimeException](class.runtimeexception) if `name` is already declared as a property php None Type Juggling ------------- PHP does not require explicit type definition in variable declaration. In this case, the type of a variable is determined by the value it stores. That is to say, if a string is assigned to variable $var, then $var is of type string. If afterwards an int value is assigned to $var, it will be of type int. PHP may attempt to convert the type of a value to another automatically in certain contexts. The different contexts which exist are: * Numeric * String * Logical * Integral and string * Comparative * Function > **Note**: When a value needs to be interpreted as a different type, the value itself does *not* change types. > > To force a variable to be evaluated as a certain type, see the section on [Type casting](language.types.type-juggling#language.types.typecasting). To change the type of a variable, see the [settype()](function.settype) function. ### Numeric contexts This is the context when using an [arithmetical operator](language.operators.arithmetic). In this context if either operand is a float (or not interpretable as an int), both operands are interpreted as floats, and the result will be a float. Otherwise, the operands will be interpreted as ints, and the result will also be an int. As of PHP 8.0.0, if one of the operands cannot be interpreted a [TypeError](class.typeerror) is thrown. ### String contexts This is the context when using [echo](function.echo), [print](function.print), [string interpolation](language.types.string#language.types.string.parsing), or the string [concatenation operator](language.operators.string). In this context the value will be interpreted as string. If the value cannot be interpreted a [TypeError](class.typeerror) is thrown. Prior to PHP 7.4.0, an **`E_RECOVERABLE_ERROR`** was raised. ### Logical contexts This is the context when using conditional statements, the [ternary operator](language.operators.comparison#language.operators.comparison.ternary), or a [logical operator](language.operators.logical). In this context the value will be interpreted as bool. ### Integral and string contexts This is the context when using a [bitwise operators](language.operators.bitwise). In this context if all operands are of type string the result will also be a string. Otherwise, the operands will be interpreted as ints, and the result will also be an int. As of PHP 8.0.0, if one of the operands cannot be interpreted a [TypeError](class.typeerror) is thrown. ### Comparative contexts This is the context when using a [comparison operator](language.operators.comparison). The type conversions which occur in this context are explained in the Comparison with Various Types [table](language.operators.comparison#language.operators.comparison.types). ### Function contexts This is the context when a value is passed to a typed parameter, property, or returned from a function which declares a return type. In this context the value must be a value of the type. Two exceptions exist, the first one is: if the value is of type int and the declared type is float, then the integer is converted to a floating point number. The second one is: if the value and the declared type are *scalar* types, and the coercive typing mode is active (the default), the value may be converted to an accepted scalar valued. See below for a description of this behaviour. **Warning** [Internal functions](functions.internal) automatically coerce **`null`** to scalar types, this behaviour is *DEPRECATED* as of PHP 8.1.0. #### Coercive typing with simple type declarations * bool type declaration: value is interpreted as bool. * int type declaration: value is interpreted as int if conversion is well-defined. I.e. the string is [numeric](language.types.numeric-strings). * float type declaration: value is interpreted as float if conversion is well-defined. I.e. the string is [numeric](language.types.numeric-strings). * string type declaration: value is interpreted as string. #### Coercive typing with union types When `strict_types` is not enabled, scalar type declarations are subject to limited implicit type coercions. If the exact type of the value is not part of the union, then the target type is chosen in the following order of preference: 1. int 2. float 3. string 4. bool If the type both exists in the union, and the value can be coerced to the type under PHPs existing type checking semantics, then the type is chosen. Otherwise, the next type is tried. **Caution** As an exception, if the value is a string and both int and float are part of the union, the preferred type is determined by the existing “numeric string” semantics. For example, for `"42"` int is chosen, while for `"42.0"` float is chosen. > > **Note**: > > > Types that are not part of the above preference list are not eligible targets for implicit coercion. In particular no implicit coercions to the `null` and `false` types occur. > > **Example #1 Example of types being coerced into a type part of the union** ``` <?php // int|string 42    --> 42          // exact type "42"  --> "42"        // exact type new ObjectWithToString --> "Result of __toString()"                       // object never compatible with int, fall back to string 42.0  --> 42          // float compatible with int 42.1  --> 42          // float compatible with int 1e100 --> "1.0E+100"  // float too large for int type, fall back to string INF   --> "INF"       // float too large for int type, fall back to string true  --> 1           // bool compatible with int []    --> TypeError   // array not compatible with int or string // int|float|bool "45"    --> 45        // int numeric string "45.0"  --> 45.0      // float numeric string "45X"   --> true      // not numeric string, fall back to bool ""      --> false     // not numeric string, fall back to bool "X"     --> true      // not numeric string, fall back to bool []      --> TypeError // array not compatible with int, float or bool ?> ``` ### Type Casting Type casting converts the value to a chosen type by writing the type within parentheses before the value to convert. ``` <?php $foo = 10;   // $foo is an integer $bar = (bool) $foo;   // $bar is a boolean ?> ``` The casts allowed are: * `(int)` - cast to int * `(bool)` - cast to bool * `(float)` - cast to float * `(string)` - cast to string * `(array)` - cast to array * `(object)` - cast to object * `(unset)` - cast to NULL > > **Note**: > > > `(integer)` is an alias of the `(int)` cast. `(boolean)` is an alias of the `(bool)` cast. `(binary)` is an alias of the `(string)` cast. `(double)` and `(real)` are aliases of the `(float)` cast. These casts do not use the canonical type name and are not recommended. > > **Warning** The `(real)` cast alias has been deprecated as of PHP 8.0.0. **Warning** The `(unset)` cast has been deprecated as of PHP 7.2.0. Note that the `(unset)` cast is the same as assigning the value NULL to the variable or call. The `(unset)` cast is removed as of PHP 8.0.0. **Caution** The `(binary)` cast and `b` prefix exists for forward support. Currently `(binary)` and `(string)` are identical, however this may change and should not be relied upon. > > **Note**: > > > Whitespaces are ignored within the parentheses of a cast. Therefore, the following are two casts are equivalent: > > > > ``` > <?php > $foo = (int) $bar; > $foo = ( int ) $bar; > ?> > ``` > Casting literal strings and variables to binary strings: ``` <?php $binary = (binary) $string; $binary = b"binary string"; ?> ``` > > **Note**: Instead of casting a variable to a string, it is also possible to enclose the variable in double quotes. > > > > ``` > <?php > $foo = 10;            // $foo is an integer > $str = "$foo";        // $str is a string > $fst = (string) $foo; // $fst is also a string > > // This prints out that "they are the same" > if ($fst === $str) { >     echo "they are the same"; > } > ?> > ``` > It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections: * [Converting to boolean](language.types.boolean#language.types.boolean.casting) * [Converting to integer](language.types.integer#language.types.integer.casting) * [Converting to float](language.types.float#language.types.float.casting) * [Converting to string](language.types.string#language.types.string.casting) * [Converting to array](language.types.array#language.types.array.casting) * [Converting to object](language.types.object#language.types.object.casting) * [Converting to resource](language.types.resource#language.types.resource.casting) * [Converting to NULL](language.types.null#language.types.null.casting) * [The type comparison tables](https://www.php.net/manual/en/types.comparisons.php) > > **Note**: Because PHP supports indexing into strings via offsets using the same syntax as array indexing, the following example holds true for all PHP versions: > > > > ``` > <?php > $a    = 'car'; // $a is a string > $a[0] = 'b';   // $a is still a string > echo $a;       // bar > ?> > ``` > See the section titled [String access by character](language.types.string#language.types.string.substr) for more information.
programming_docs
php ImagickKernel::separate ImagickKernel::separate ======================= (PECL imagick >= 3.3.0) ImagickKernel::separate — Description ### Description ``` public ImagickKernel::separate(): array ``` Separates a linked set of kernels and returns an array of ImagickKernels. ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **ImagickKernel::separate()**** ``` <?php          function renderKernelTable($matrix) {         $output = "<table class='infoTable'>";         foreach ($matrix as $row) {             $output .= "<tr>";             foreach ($row as $cell) {                 $output .= "<td style='text-align:left'>";                 if ($cell === false) {                     $output .= "false";                 }                 else {                     $output .= round($cell, 3);                 }                 $output .= "</td>";             }             $output .= "</tr>";         }              $output .= "</table>";              return $output;     }     $matrix = [         [-1, 0, -1],         [ 0, 4,  0],         [-1, 0, -1],     ];     $kernel = \ImagickKernel::fromMatrix($matrix);     $kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);     $diamondKernel = \ImagickKernel::fromBuiltIn(         \Imagick::KERNEL_DIAMOND,         "2"     );     $kernel->addKernel($diamondKernel);          $kernelList = $kernel->separate();          $output = '';     $count = 0;     foreach ($kernelList as $kernel) {         $output .= "<br/>Kernel $count<br/>";         $output .= renderKernelTable($kernel->getMatrix());         $count++;     }     return $output; ?> ``` php Imagick::setImageFilename Imagick::setImageFilename ========================= (PECL imagick 2, PECL imagick 3) Imagick::setImageFilename — Sets the filename of a particular image ### Description ``` public Imagick::setImageFilename(string $filename): bool ``` Sets the filename of a particular image in a sequence. ### Parameters `filename` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php ReflectionProperty::isPromoted ReflectionProperty::isPromoted ============================== (PHP 8) ReflectionProperty::isPromoted — Checks if property is promoted ### Description ``` public ReflectionProperty::isPromoted(): bool ``` Checks whether the property is [promoted](language.oop5.decon#language.oop5.decon.constructor.promotion) ### Parameters This function has no parameters. ### Return Values **`true`** if the property is promoted, **`false`** otherwise. ### Examples **Example #1 **ReflectionProperty::isPromoted()** example** ``` <?php class Foo {     public $baz;     public function __construct(public $bar) {} } $o = new Foo(42); $o->baz = 42; $ro = new ReflectionObject($o); var_dump($ro->getProperty('bar')->isPromoted()); var_dump($ro->getProperty('baz')->isPromoted()); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [ReflectionProperty::isDefault()](reflectionproperty.isdefault) - Checks if property is a default property * [ReflectionProperty::isInitialized()](reflectionproperty.isinitialized) - Checks whether a property is initialized * [ReflectionProperty::getValue()](reflectionproperty.getvalue) - Gets value php ReflectionExtension::getConstants ReflectionExtension::getConstants ================================= (PHP 5, PHP 7, PHP 8) ReflectionExtension::getConstants — Gets constants ### Description ``` public ReflectionExtension::getConstants(): array ``` Get defined constants from an extension. ### Parameters This function has no parameters. ### Return Values An associative array with constant names as keys. ### Examples **Example #1 **ReflectionExtension::getConstants()** example** ``` <?php $ext = new ReflectionExtension('DOM'); print_r($ext->getConstants()); ?> ``` The above example will output something similar to: ``` Array ( [XML_ELEMENT_NODE] => 1 [XML_ATTRIBUTE_NODE] => 2 [XML_TEXT_NODE] => 3 [XML_CDATA_SECTION_NODE] => 4 [XML_ENTITY_REF_NODE] => 5 [XML_ENTITY_NODE] => 6 [XML_PI_NODE] => 7 [XML_COMMENT_NODE] => 8 [XML_DOCUMENT_NODE] => 9 [XML_DOCUMENT_TYPE_NODE] => 10 [XML_DOCUMENT_FRAG_NODE] => 11 [XML_NOTATION_NODE] => 12 [XML_HTML_DOCUMENT_NODE] => 13 [XML_DTD_NODE] => 14 [XML_ELEMENT_DECL_NODE] => 15 [XML_ATTRIBUTE_DECL_NODE] => 16 [XML_ENTITY_DECL_NODE] => 17 [XML_NAMESPACE_DECL_NODE] => 18 [XML_LOCAL_NAMESPACE] => 18 [XML_ATTRIBUTE_CDATA] => 1 [XML_ATTRIBUTE_ID] => 2 [XML_ATTRIBUTE_IDREF] => 3 [XML_ATTRIBUTE_IDREFS] => 4 [XML_ATTRIBUTE_ENTITY] => 6 [XML_ATTRIBUTE_NMTOKEN] => 7 [XML_ATTRIBUTE_NMTOKENS] => 8 [XML_ATTRIBUTE_ENUMERATION] => 9 [XML_ATTRIBUTE_NOTATION] => 10 [DOM_PHP_ERR] => 0 [DOM_INDEX_SIZE_ERR] => 1 [DOMSTRING_SIZE_ERR] => 2 [DOM_HIERARCHY_REQUEST_ERR] => 3 [DOM_WRONG_DOCUMENT_ERR] => 4 [DOM_INVALID_CHARACTER_ERR] => 5 [DOM_NO_DATA_ALLOWED_ERR] => 6 [DOM_NO_MODIFICATION_ALLOWED_ERR] => 7 [DOM_NOT_FOUND_ERR] => 8 [DOM_NOT_SUPPORTED_ERR] => 9 [DOM_INUSE_ATTRIBUTE_ERR] => 10 [DOM_INVALID_STATE_ERR] => 11 [DOM_SYNTAX_ERR] => 12 [DOM_INVALID_MODIFICATION_ERR] => 13 [DOM_NAMESPACE_ERR] => 14 [DOM_INVALID_ACCESS_ERR] => 15 [DOM_VALIDATION_ERR] => 16 ) ``` ### See Also * [ReflectionExtension::getINIEntries()](reflectionextension.getinientries) - Gets extension ini entries php array_diff array\_diff =========== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) array\_diff — Computes the difference of arrays ### Description ``` array_diff(array $array, array ...$arrays): array ``` Compares `array` against one or more other arrays and returns the values in `array` that are not present in any of the other arrays. ### Parameters `array` The array to compare from `arrays` Arrays to compare against ### Return Values Returns an array containing all the entries from `array` that are not present in any of the other arrays. Keys in the `array` array are preserved. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function can now be called with only one parameter. Formerly, at least two parameters have been required. | ### Examples **Example #1 **array\_diff()** example** ``` <?php $array1 = array("a" => "green", "red", "blue", "red"); $array2 = array("b" => "green", "yellow", "red"); $result = array_diff($array1, $array2); print_r($result); ?> ``` Multiple occurrences in $array1 are all treated the same way. This will output : ``` Array ( [1] => blue ) ``` **Example #2 **array\_diff()** example with non-matching types** Two elements are considered equal if and only if `(string) $elem1 === (string) $elem2`. That is, when the [string representation](language.types.string#language.types.string.casting) is the same. ``` <?php // This will generate a Notice that an array cannot be cast to a string. $source = [1, 2, 3, 4]; $filter = [3, 4, [5], 6]; $result = array_diff($source, $filter); // Whereas this is fine, since the objects can cast to a string. class S {   private $v;   public function __construct(string $v) {     $this->v = $v;   }   public function __toString() {     return $this->v;   } } $source = [new S('a'), new S('b'), new S('c')]; $filter = [new S('b'), new S('c'), new S('d')]; $result = array_diff($source, $filter); // $result now contains one instance of S('a'); ?> ``` To use an alternate comparison function, see [array\_udiff()](function.array-udiff). ### Notes > > **Note**: > > > This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using `array_diff($array1[0], $array2[0]);`. > > ### See Also * [array\_diff\_assoc()](function.array-diff-assoc) - Computes the difference of arrays with additional index check * [array\_udiff()](function.array-udiff) - Computes the difference of arrays by using a callback function for data comparison * [array\_intersect()](function.array-intersect) - Computes the intersection of arrays * [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check php GmagickDraw::getstrokeopacity GmagickDraw::getstrokeopacity ============================= (PECL gmagick >= Unknown) GmagickDraw::getstrokeopacity — Returns the opacity of stroked object outlines ### Description ``` public GmagickDraw::getstrokeopacity(): float ``` Returns the opacity of stroked object outlines. ### Parameters This function has no parameters. ### Return Values Returns a float describing the opacity. php snmp_set_enum_print snmp\_set\_enum\_print ====================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) snmp\_set\_enum\_print — Return all values that are enums with their enum value instead of the raw integer ### Description ``` snmp_set_enum_print(bool $enable): bool ``` This function toggles if snmpwalk/snmpget etc. should automatically lookup enum values in the MIB and return them together with their human readable string. ### Parameters `enable` As the value is interpreted as boolean by the Net-SNMP library, it can only be "0" or "1". ### Return Values Always returns **`true`**. ### Examples **Example #1 Using **snmp\_set\_enum\_print()**** ``` <?php  snmp_set_enum_print(0);  echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n";  snmp_set_enum_print(1);  echo snmpget('localhost', 'public', 'IF-MIB::ifOperStatus.3') . "\n"; ?> ``` The above would return ``` INTEGER: up(1) INTEGER: 1 ``` php GmagickDraw::scale GmagickDraw::scale ================== (PECL gmagick >= Unknown) GmagickDraw::scale — Adjusts the scaling factor ### Description ``` public GmagickDraw::scale(float $x, float $y): GmagickDraw ``` Adjusts the scaling factor to apply in the horizontal and vertical directions to the current coordinate space. ### Parameters `x` horizontal scale factor `y` vertical scale factor ### Return Values The [GmagickDraw](class.gmagickdraw) object. php socket_connect socket\_connect =============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_connect — Initiates a connection on a socket ### Description ``` socket_connect(Socket $socket, string $address, ?int $port = null): bool ``` Initiate a connection to `address` using the [Socket](class.socket) instance `socket`, which must be [Socket](class.socket) instance created with [socket\_create()](function.socket-create). ### Parameters `socket` A [Socket](class.socket) instance created with [socket\_create()](function.socket-create). `address` The `address` parameter is either an IPv4 address in dotted-quad notation (e.g. `127.0.0.1`) if `socket` is **`AF_INET`**, a valid IPv6 address (e.g. `::1`) if IPv6 support is enabled and `socket` is **`AF_INET6`** or the pathname of a Unix domain socket, if the socket family is **`AF_UNIX`**. `port` The `port` parameter is only used and is mandatory when connecting to an **`AF_INET`** or an **`AF_INET6`** socket, and designates the port on the remote host to which a connection should be made. ### Return Values Returns **`true`** on success or **`false`** on failure. The error code can be retrieved with [socket\_last\_error()](function.socket-last-error). This code may be passed to [socket\_strerror()](function.socket-strerror) to get a textual explanation of the error. > > **Note**: > > > If the socket is non-blocking then this function returns **`false`** with an error `Operation now in progress`. > > ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | | 8.0.0 | `port` is nullable now. | ### See Also * [socket\_bind()](function.socket-bind) - Binds a name to a socket * [socket\_listen()](function.socket-listen) - Listens for a connection on a socket * [socket\_create()](function.socket-create) - Create a socket (endpoint for communication) * [socket\_last\_error()](function.socket-last-error) - Returns the last error on the socket * [socket\_strerror()](function.socket-strerror) - Return a string describing a socket error php mysqli_stmt::execute mysqli\_stmt::execute ===================== mysqli\_stmt\_execute ===================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::execute -- mysqli\_stmt\_execute — Executes a prepared statement ### Description Object-oriented style ``` public mysqli_stmt::execute(?array $params = null): bool ``` Procedural style ``` mysqli_stmt_execute(mysqli_stmt $statement, ?array $params = null): bool ``` Executes previously prepared statement. The statement must be successfully prepared prior to execution, using either the [mysqli\_prepare()](mysqli.prepare) or [mysqli\_stmt\_prepare()](mysqli-stmt.prepare) function, or by passing the second argument to [mysqli\_stmt::\_\_construct()](mysqli-stmt.construct). If the statement is `UPDATE`, `DELETE`, or `INSERT`, the total number of affected rows can be determined by using the [mysqli\_stmt\_affected\_rows()](mysqli-stmt.affected-rows) function. If the query yields a result set, it can be fetched using [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) function or by fetching it row by row directly from the statement using [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) function. ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). `params` An optional list array with as many elements as there are bound parameters in the SQL statement being executed. Each value is treated as a string. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The optional `params` parameter has been added. | ### Examples **Example #1 Execute a prepared statement with bound variables** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $mysqli->query("CREATE TEMPORARY TABLE myCity LIKE City"); /* Prepare an insert statement */ $stmt = $mysqli->prepare("INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)"); /* Bind variables to parameters */ $stmt->bind_param("sss", $val1, $val2, $val3); $val1 = 'Stuttgart'; $val2 = 'DEU'; $val3 = 'Baden-Wuerttemberg'; /* Execute the statement */ $stmt->execute(); $val1 = 'Bordeaux'; $val2 = 'FRA'; $val3 = 'Aquitaine'; /* Execute the statement */ $stmt->execute(); /* Retrieve all rows from myCity */ $query = "SELECT Name, CountryCode, District FROM myCity"; $result = $mysqli->query($query); while ($row = $result->fetch_row()) {     printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); } ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); mysqli_query($link, "CREATE TEMPORARY TABLE myCity LIKE City"); /* Prepare an insert statement */ $stmt = mysqli_prepare($link, "INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)"); /* Bind variables to parameters */ mysqli_stmt_bind_param($stmt, "sss", $val1, $val2, $val3); $val1 = 'Stuttgart'; $val2 = 'DEU'; $val3 = 'Baden-Wuerttemberg'; /* Execute the statement */ mysqli_stmt_execute($stmt); $val1 = 'Bordeaux'; $val2 = 'FRA'; $val3 = 'Aquitaine'; /* Execute the statement */ mysqli_stmt_execute($stmt); /* Retrieve all rows from myCity */ $query = "SELECT Name, CountryCode, District FROM myCity"; $result = mysqli_query($link, $query); while ($row = mysqli_fetch_row($result)) {     printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); } ``` The above examples will output: ``` Stuttgart (DEU,Baden-Wuerttemberg) Bordeaux (FRA,Aquitaine) ``` **Example #2 Execute a prepared statement with an array of values** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); $mysqli->query('CREATE TEMPORARY TABLE myCity LIKE City'); /* Prepare an insert statement */ $stmt = $mysqli->prepare('INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)'); /* Execute the statement */ $stmt->execute(['Stuttgart', 'DEU', 'Baden-Wuerttemberg']); /* Retrieve all rows from myCity */ $query = 'SELECT Name, CountryCode, District FROM myCity'; $result = $mysqli->query($query); while ($row = $result->fetch_row()) {     printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); } ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect('localhost', 'my_user', 'my_password', 'world'); mysqli_query($link, 'CREATE TEMPORARY TABLE myCity LIKE City'); /* Prepare an insert statement */ $stmt = mysqli_prepare($link, 'INSERT INTO myCity (Name, CountryCode, District) VALUES (?,?,?)'); /* Execute the statement */ mysqli_stmt_execute($stmt, ['Stuttgart', 'DEU', 'Baden-Wuerttemberg']); /* Retrieve all rows from myCity */ $query = 'SELECT Name, CountryCode, District FROM myCity'; $result = mysqli_query($link, $query); while ($row = mysqli_fetch_row($result)) {     printf("%s (%s,%s)\n", $row[0], $row[1], $row[2]); } ``` The above examples will output: ``` Stuttgart (DEU,Baden-Wuerttemberg) ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) - Binds variables to a prepared statement as parameters * [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) - Gets a result set from a prepared statement as a mysqli\_result object php FilesystemIterator::next FilesystemIterator::next ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) FilesystemIterator::next — Move to the next file ### Description ``` public FilesystemIterator::next(): void ``` Move to the next file. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **FilesystemIterator::next()** example** List the contents of a directory using a while loop. ``` <?php $iterator = new FilesystemIterator(dirname(__FILE__)); while($iterator->valid()) {     echo $iterator->getFilename() . "\n";     $iterator->next(); } ?> ``` The above example will output something similar to: ``` apple.jpg banana.jpg example.php ``` ### See Also * [DirectoryIterator::next()](directoryiterator.next) - Move forward to next DirectoryIterator item php gzcompress gzcompress ========== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) gzcompress — Compress a string ### Description ``` gzcompress(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_DEFLATE): string|false ``` This function compresses the given string using the `ZLIB` data format. For details on the ZLIB compression algorithm see the document "[» ZLIB Compressed Data Format Specification version 3.3](http://www.faqs.org/rfcs/rfc1950)" (RFC 1950). > > **Note**: > > > This is *not* the same as gzip compression, which includes some header data. See [gzencode()](function.gzencode) for gzip compression. > > ### Parameters `data` The data to compress. `level` The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If -1 is used, the default compression of the zlib library is used which is 6. `encoding` One of **`ZLIB_ENCODING_*`** constants. ### Return Values The compressed string or **`false`** if an error occurred. ### Examples **Example #1 **gzcompress()** example** ``` <?php $compressed = gzcompress('Compress me', 9); echo $compressed; ?> ``` ### See Also * [gzdeflate()](function.gzdeflate) - Deflate a string * [gzinflate()](function.gzinflate) - Inflate a deflated string * [gzuncompress()](function.gzuncompress) - Uncompress a compressed string * [gzencode()](function.gzencode) - Create a gzip compressed string
programming_docs
php Operators Operators ========= Table of Contents ----------------- * [Operator Precedence](language.operators.precedence) * [Arithmetic Operators](language.operators.arithmetic) * [Assignment Operators](language.operators.assignment) * [Bitwise Operators](language.operators.bitwise) * [Comparison Operators](language.operators.comparison) * [Error Control Operators](language.operators.errorcontrol) * [Execution Operators](language.operators.execution) * [Incrementing/Decrementing Operators](language.operators.increment) * [Logical Operators](language.operators.logical) * [String Operators](language.operators.string) * [Array Operators](language.operators.array) * [Type Operators](language.operators.type) An operator is something that takes one or more values (or expressions, in programming jargon) and yields another value (so that the construction itself becomes an expression). Operators can be grouped according to the number of values they take. Unary operators take only one value, for example `!` (the [logical not operator](language.operators.logical)) or `++` (the [increment operator](language.operators.increment)). Binary operators take two values, such as the familiar [arithmetical operators](language.operators.arithmetic) `+` (plus) and `-` (minus), and the majority of PHP operators fall into this category. Finally, there is a single [ternary operator](language.operators.comparison#language.operators.comparison.ternary), `? :`, which takes three values; this is usually referred to simply as "the ternary operator" (although it could perhaps more properly be called the conditional operator). A full list of PHP operators follows in the section [Operator Precedence](language.operators.precedence). The section also explains operator precedence and associativity, which govern exactly how expressions containing several different operators are evaluated. php SolrIllegalOperationException::getInternalInfo SolrIllegalOperationException::getInternalInfo ============================================== (PECL solr >= 0.9.2) SolrIllegalOperationException::getInternalInfo — Returns internal information where the Exception was thrown ### Description ``` public SolrIllegalOperationException::getInternalInfo(): array ``` Returns internal information where the Exception was thrown. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns an array containing internal information where the error was thrown. Used only for debugging by extension developers. php DirectoryIterator::rewind DirectoryIterator::rewind ========================= (PHP 5, PHP 7, PHP 8) DirectoryIterator::rewind — Rewind the DirectoryIterator back to the start ### Description ``` public DirectoryIterator::rewind(): void ``` Rewind the [DirectoryIterator](class.directoryiterator) back to the start. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **DirectoryIterator::rewind()** example** ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); $iterator->next(); echo $iterator->key(); //1 $iterator->rewind(); //rewinding to the beginning echo $iterator->key(); //0 ?> ``` ### See Also * [DirectoryIterator::current()](directoryiterator.current) - Return the current DirectoryIterator item * [DirectoryIterator::key()](directoryiterator.key) - Return the key for the current DirectoryIterator item * [DirectoryIterator::next()](directoryiterator.next) - Move forward to next DirectoryIterator item * [DirectoryIterator::valid()](directoryiterator.valid) - Check whether current DirectoryIterator position is a valid file * [Iterator::rewind()](iterator.rewind) - Rewind the Iterator to the first element php end end === (PHP 4, PHP 5, PHP 7, PHP 8) end — Set the internal pointer of an array to its last element ### Description ``` end(array|object &$array): mixed ``` **end()** advances `array`'s internal pointer to the last element, and returns its value. ### Parameters `array` The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference. ### Return Values Returns the value of the last element or **`false`** for empty array. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function on objects is deprecated. Either use [get\_mangled\_object\_vars()](function.get-mangled-object-vars) on the object first, or use [ArrayIterator](class.arrayiterator). | ### Examples **Example #1 **end()** example** ``` <?php $fruits = array('apple', 'banana', 'cranberry'); echo end($fruits); // cranberry ?> ``` ### See Also * [current()](function.current) - Return the current element in an array * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor * [prev()](function.prev) - Rewind the internal array pointer * [reset()](function.reset) - Set the internal pointer of an array to its first element * [next()](function.next) - Advance the internal pointer of an array * [array\_key\_last()](function.array-key-last) - Gets the last key of an array php pg_unescape_bytea pg\_unescape\_bytea =================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_unescape\_bytea — Unescape binary for bytea type ### Description ``` pg_unescape_bytea(string $string): string ``` **pg\_unescape\_bytea()** unescapes PostgreSQL bytea data values. It returns the unescaped string, possibly containing binary data. > > **Note**: > > > When you `SELECT` a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually. > > This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. `INSERT INTO test_table (image) > VALUES ('$image_escaped'::bytea);` PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error. > > ### Parameters `string` A string containing PostgreSQL bytea data to be converted into a PHP binary string. ### Return Values A string containing the unescaped data. ### Examples **Example #1 **pg\_unescape\_bytea()** example** ``` <?php    // Connect to the database   $dbconn = pg_connect('dbname=foo');      // Get the bytea data   $res = pg_query("SELECT data FROM gallery WHERE name='Pine trees'");     $raw = pg_fetch_result($res, 'data');      // Convert to binary and send to the browser   header('Content-type: image/jpeg');   echo pg_unescape_bytea($raw); ?> ``` ### See Also * [pg\_escape\_bytea()](function.pg-escape-bytea) - Escape a string for insertion into a bytea field * [pg\_escape\_string()](function.pg-escape-string) - Escape a string for query php Ds\Stack::toArray Ds\Stack::toArray ================= (PECL ds >= 1.0.0) Ds\Stack::toArray — Converts the stack to an array ### Description ``` public Ds\Stack::toArray(): array ``` Converts the stack to an array. > > **Note**: > > > Casting to an array is not supported yet. > > ### Parameters This function has no parameters. ### Return Values An array containing all the values in the same order as the stack. ### Examples **Example #1 **Ds\Stack::toArray()** example** ``` <?php $stack = new \Ds\Stack([1, 2, 3]); var_dump($stack->toArray()); ?> ``` The above example will output something similar to: ``` array(3) { [0]=> int(3) [1]=> int(2) [2]=> int(1) } ``` php mysqli_result::fetch_field_direct mysqli\_result::fetch\_field\_direct ==================================== mysqli\_fetch\_field\_direct ============================ (PHP 5, PHP 7, PHP 8) mysqli\_result::fetch\_field\_direct -- mysqli\_fetch\_field\_direct — Fetch meta-data for a single field ### Description Object-oriented style ``` public mysqli_result::fetch_field_direct(int $index): object|false ``` Procedural style ``` mysqli_fetch_field_direct(mysqli_result $result, int $index): object|false ``` Returns an object which contains field definition information from the specified result set. ### Parameters `result` Procedural style only: A [mysqli\_result](class.mysqli-result) object returned by [mysqli\_query()](mysqli.query), [mysqli\_store\_result()](mysqli.store-result), [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). `index` The field number. This value must be in the range from `0` to `number of fields - 1`. ### Return Values Returns an object which contains field definition information or **`false`** if no field information for specified `fieldnr` is available. **Object attributes**| Attribute | Description | | --- | --- | | name | The name of the column | | orgname | Original column name if an alias was specified | | table | The name of the table this field belongs to (if not calculated) | | orgtable | Original table name if an alias was specified | | def | The default value for this field, represented as a string | | max\_length | The maximum width of the field for the result set. | | length | The width of the field, as specified in the table definition. | | charsetnr | The character set number for the field. | | flags | An integer representing the bit-flags for the field. | | type | The data type used for this field | | decimals | The number of decimals used (for numeric fields) | ### Examples **Example #1 Object-oriented style** ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5"; if ($result = $mysqli->query($query)) {     /* Get field information for column 'SurfaceArea' */     $finfo = $result->fetch_field_direct(1);     printf("Name:     %s\n", $finfo->name);     printf("Table:    %s\n", $finfo->table);     printf("max. Len: %d\n", $finfo->max_length);     printf("Flags:    %d\n", $finfo->flags);     printf("Type:     %d\n", $finfo->type);     $result->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $query = "SELECT Name, SurfaceArea from Country ORDER BY Name LIMIT 5"; if ($result = mysqli_query($link, $query)) {     /* Get field information for column 'SurfaceArea' */     $finfo = mysqli_fetch_field_direct($result, 1);     printf("Name:     %s\n", $finfo->name);     printf("Table:    %s\n", $finfo->table);     printf("max. Len: %d\n", $finfo->max_length);     printf("Flags:    %d\n", $finfo->flags);     printf("Type:     %d\n", $finfo->type);     mysqli_free_result($result); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Name: SurfaceArea Table: Country max. Len: 10 Flags: 32769 Type: 4 ``` ### See Also * [mysqli\_num\_fields()](mysqli-result.field-count) - Gets the number of fields in the result set * [mysqli\_fetch\_field()](mysqli-result.fetch-field) - Returns the next field in the result set * [mysqli\_fetch\_fields()](mysqli-result.fetch-fields) - Returns an array of objects representing the fields in a result set php jdtojulian jdtojulian ========== (PHP 4, PHP 5, PHP 7, PHP 8) jdtojulian — Converts a Julian Day Count to a Julian Calendar Date ### Description ``` jdtojulian(int $julian_day): string ``` Converts Julian Day Count to a string containing the Julian Calendar Date in the format of "month/day/year". ### Parameters `julian_day` A julian day number as integer ### Return Values The julian date as a string in the form "month/day/year" ### See Also * [juliantojd()](function.juliantojd) - Converts a Julian Calendar date to Julian Day Count * [cal\_from\_jd()](function.cal-from-jd) - Converts from Julian Day Count to a supported calendar php sqlsrv_send_stream_data sqlsrv\_send\_stream\_data ========================== (No version information available, might only be in Git) sqlsrv\_send\_stream\_data — Sends data from parameter streams to the server ### Description ``` sqlsrv_send_stream_data(resource $stmt): bool ``` Send data from parameter streams to the server. Up to 8 KB of data is sent with each call. ### Parameters `stmt` A statement resource returned by [sqlsrv\_query()](function.sqlsrv-query) or [sqlsrv\_execute()](function.sqlsrv-execute). ### Return Values Returns **`true`** if there is more data to send and **`false`** if there is not. ### Examples **Example #1 **sqlsrv\_send\_stream\_data()** example** ``` <?php $serverName = "serverName\sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" ); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } $sql = "UPDATE Table_1 SET data = ( ?) WHERE id = 100"; // Open parameter data as a stream and put it in the $params array. $data = fopen( "data://text/plain,[ Lengthy content here. ]", "r"); $params = array( &$data); // Prepare the statement. Use the $options array to turn off the // default behavior, which is to send all stream data at the time of query // execution. $options = array("SendStreamParamsAtExec"=>0); $stmt = sqlsrv_prepare( $conn, $sql, $params, $options); sqlsrv_execute( $stmt); // Send up to 8K of parameter data to the server  // with each call to sqlsrv_send_stream_data. $i = 1; while( sqlsrv_send_stream_data( $stmt)) {       $i++; } echo "$i calls were made."; ?> ``` ### See Also * [sqlsrv\_prepare()](function.sqlsrv-prepare) - Prepares a query for execution * [sqlsrv\_query()](function.sqlsrv-query) - Prepares and executes a query php ImagickDraw::pushDefs ImagickDraw::pushDefs ===================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pushDefs — Indicates that following commands create named elements for early processing ### Description ``` public ImagickDraw::pushDefs(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Indicates that commands up to a terminating [ImagickDraw::popDefs()](imagickdraw.popdefs) command create named elements (e.g. clip-paths, textures, etc.) which may safely be processed earlier for the sake of efficiency. ### Return Values No value is returned. php GmagickDraw::getfontstyle GmagickDraw::getfontstyle ========================= (PECL gmagick >= Unknown) GmagickDraw::getfontstyle — Returns the font style ### Description ``` public GmagickDraw::getfontstyle(): int ``` Returns the font style used when annotating with text. ### Parameters This function has no parameters. ### Return Values Returns the font style constant (STYLE\_) associated with the [GmagickDraw](class.gmagickdraw) object or `0` if no style is set. php Imagick::getOption Imagick::getOption ================== (PECL imagick 2, PECL imagick 3) Imagick::getOption — Returns a value associated with the specified key ### Description ``` public Imagick::getOption(string $key): string ``` Returns a value associated within the object for the specified key. ### Parameters `key` The name of the option ### Return Values Returns a value associated with a wand and the specified key. ### Errors/Exceptions Throws ImagickException on error. php ImagickDraw::setFontStyle ImagickDraw::setFontStyle ========================= (PECL imagick 2, PECL imagick 3) ImagickDraw::setFontStyle — Sets the font style to use when annotating with text ### Description ``` public ImagickDraw::setFontStyle(int $style): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the font style to use when annotating with text. The AnyStyle enumeration acts as a wild-card "don't care" option. ### Parameters `style` One of the [STYLE](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.styles) constant (`imagick::STYLE_*`). ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setFontStyle()** example** ``` <?php function setFontStyle($fillColor, $strokeColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(1);     $draw->setFontSize(36);     $draw->setFontStyle(\Imagick::STYLE_NORMAL);     $draw->annotation(50, 50, "Lorem Ipsum!");     $draw->setFontStyle(\Imagick::STYLE_ITALIC);     $draw->annotation(50, 100, "Lorem Ipsum!");     $draw->setFontStyle(\Imagick::STYLE_OBLIQUE);     $draw->annotation(50, 150, "Lorem Ipsum!");     $imagick = new \Imagick();     $imagick->newImage(350, 300, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php IntlCalendar::inDaylightTime IntlCalendar::inDaylightTime ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::inDaylightTime — Whether the objectʼs time is in Daylight Savings Time ### Description Object-oriented style ``` public IntlCalendar::inDaylightTime(): bool ``` Procedural style ``` intlcal_in_daylight_time(IntlCalendar $calendar): bool ``` Whether, for the instant represented by this object and for this objectʼs timezone, daylight saving time is in place. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. ### Return Values Returns **`true`** if the date is in Daylight Savings Time, **`false`** otherwise. On failure **`false`** is also returned. To detect error conditions use [intl\_get\_error\_code()](function.intl-get-error-code), or set up Intl to throw [exceptions](https://www.php.net/manual/en/intl.configuration.php#ini.intl.use-exceptions). ### Examples **Example #1 **IntlCalendar::inDaylightTime()**** ``` <?php ini_set('date.timezone', 'Europe/Lisbon'); ini_set('intl.default_locale', 'pt_PT'); $cal = new IntlGregorianCalendar(2013, 6 /* July */, 1, 4, 56, 31); var_dump($cal->inDaylightTime()); // true $cal->set(IntlCalendar::FIELD_MONTH, 11 /* December */); var_dump($cal->inDaylightTime()); // false //DST end transition on 2013-10-27 at 0200 (wall time back 1 hour) $cal = new IntlGregorianCalendar(2013, 9 /* October */, 27, 1, 30, 0); var_dump($cal->inDaylightTime()); // false (default WALLTIME_LAST) $cal->setRepeatedWallTimeOption(IntlCalendar::WALLTIME_FIRST); $cal->set(IntlCalendar::FIELD_HOUR_OF_DAY, 1); // force time recalculation var_dump($cal->inDaylightTime()); // true ``` php streamWrapper::dir_rewinddir streamWrapper::dir\_rewinddir ============================= (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::dir\_rewinddir — Rewind directory handle ### Description ``` public streamWrapper::dir_rewinddir(): bool ``` This method is called in response to [rewinddir()](function.rewinddir). Should reset the output generated by [streamWrapper::dir\_readdir()](streamwrapper.dir-readdir). i.e.: The next call to [streamWrapper::dir\_readdir()](streamwrapper.dir-readdir) should return the first entry in the location returned by [streamWrapper::dir\_opendir()](streamwrapper.dir-opendir). ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [rewinddir()](function.rewinddir) - Rewind directory handle * [streamWrapper::dir\_readdir()](streamwrapper.dir-readdir) - Read entry from directory handle
programming_docs
php SplFileObject::__toString SplFileObject::\_\_toString =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::\_\_toString — Alias of [SplFileObject::fgets()](splfileobject.fgets) ### Description This method is an alias of: [SplFileObject::fgets()](splfileobject.fgets). ### Changelog | Version | Description | | --- | --- | | 7.2.19, 7.3.6 | Changed from an alias of [SplFileObject::current()](splfileobject.current) to an alias of [SplFileObject::fgets()](splfileobject.fgets). | php imagecolorallocatealpha imagecolorallocatealpha ======================= (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) imagecolorallocatealpha — Allocate a color for an image ### Description ``` imagecolorallocatealpha( GdImage $image, int $red, int $green, int $blue, int $alpha ): int|false ``` **imagecolorallocatealpha()** behaves identically to [imagecolorallocate()](function.imagecolorallocate) with the addition of the transparency parameter `alpha`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `red` Value of red component. `green` Value of green component. `blue` Value of blue component. `alpha` A value between `0` and `127`. `0` indicates completely opaque while `127` indicates completely transparent. The `red`, `green` and `blue` parameters are integers between 0 and 255 or hexadecimals between 0x00 and 0xFF. ### Return Values A color identifier or **`false`** if the allocation failed. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Example of using **imagecolorallocatealpha()**** ``` <?php $size = 300; $image=imagecreatetruecolor($size, $size); // something to get a white background with black border $back = imagecolorallocate($image, 255, 255, 255); $border = imagecolorallocate($image, 0, 0, 0); imagefilledrectangle($image, 0, 0, $size - 1, $size - 1, $back); imagerectangle($image, 0, 0, $size - 1, $size - 1, $border); $yellow_x = 100; $yellow_y = 75; $red_x    = 120; $red_y    = 165; $blue_x   = 187; $blue_y   = 125; $radius   = 150; // allocate colors with alpha values $yellow = imagecolorallocatealpha($image, 255, 255, 0, 75); $red    = imagecolorallocatealpha($image, 255, 0, 0, 75); $blue   = imagecolorallocatealpha($image, 0, 0, 255, 75); // drawing 3 overlapped circle imagefilledellipse($image, $yellow_x, $yellow_y, $radius, $radius, $yellow); imagefilledellipse($image, $red_x, $red_y, $radius, $radius, $red); imagefilledellipse($image, $blue_x, $blue_y, $radius, $radius, $blue); // don't forget to output a correct header! header('Content-Type: image/png'); // and finally, output the result imagepng($image); imagedestroy($image); ?> ``` The above example will output something similar to: **Example #2 Convert typical alpha values for use with **imagecolorallocatealpha()**** Usually alpha values of `0` designate fully transparent pixels, and the alpha channel has 8 bits. To convert such alpha values to be compatible with **imagecolorallocatealpha()**, some simple arithmetic is sufficient: ``` <?php $alpha8 = 0; // fully transparent var_dump(127 - ($alpha8 >> 1)); $alpha8 = 255; // fully opaque var_dump(127 - ($alpha8 >> 1)); ?> ``` The above example will output: ``` int(127) int(0) ``` ### See Also * [imagecolorallocate()](function.imagecolorallocate) - Allocate a color for an image * [imagecolordeallocate()](function.imagecolordeallocate) - De-allocate a color for an image php The Yaf_View_Interface class The Yaf\_View\_Interface class ============================== Introduction ------------ (Yaf >=1.0.0) Yaf provides a ability for developers to use custom view engine instead of built-in engine which is [Yaf\_View\_Simple](class.yaf-view-simple). There is a example to explain how to do this, please see [Yaf\_Dispatcher::setView()](yaf-dispatcher.setview). Class synopsis -------------- class **Yaf\_View\_Interface** { /\* Methods \*/ ``` abstract public assign(string $name, string $value = ?): bool ``` ``` abstract public display(string $tpl, array $tpl_vars = ?): bool ``` ``` abstract public getScriptPath(): void ``` ``` abstract public render(string $tpl, array $tpl_vars = ?): string ``` ``` abstract public setScriptPath(string $template_dir): void ``` } Table of Contents ----------------- * [Yaf\_View\_Interface::assign](yaf-view-interface.assign) — Assign value to View engine * [Yaf\_View\_Interface::display](yaf-view-interface.display) — Render and output a template * [Yaf\_View\_Interface::getScriptPath](yaf-view-interface.getscriptpath) — The getScriptPath purpose * [Yaf\_View\_Interface::render](yaf-view-interface.render) — Render a template * [Yaf\_View\_Interface::setScriptPath](yaf-view-interface.setscriptpath) — The setScriptPath purpose php odbc_connect odbc\_connect ============= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_connect — Connect to a datasource ### Description ``` odbc_connect( string $dsn, string $user, string $password, int $cursor_option = SQL_CUR_USE_DRIVER ): resource|false ``` The connection id returned by this functions is needed by other ODBC functions. You can have multiple connections open at once as long as they either use different db or different credentials. With some ODBC drivers, executing a complex stored procedure may fail with an error similar to: "Cannot open a cursor on a stored procedure that has anything other than a single select statement in it". Using SQL\_CUR\_USE\_ODBC may avoid that error. Also, some drivers don't support the optional row\_number parameter in [odbc\_fetch\_row()](function.odbc-fetch-row). SQL\_CUR\_USE\_ODBC might help in that case, too. ### Parameters `dsn` The database source name for the connection. Alternatively, a DSN-less connection string can be used. `user` The username. `password` The password. `cursor_option` This sets the type of cursor to be used for this connection. This parameter is not normally needed, but can be useful for working around problems with some ODBC drivers. The following constants are defined for cursortype: * SQL\_CUR\_USE\_IF\_NEEDED * SQL\_CUR\_USE\_ODBC * SQL\_CUR\_USE\_DRIVER ### Return Values Returns an ODBC connection, or **`false`** on failure. ### Examples **Example #1 DSN-less connections** ``` <?php // Microsoft SQL Server using the SQL Native Client 10.0 ODBC Driver - allows connection to SQL 7, 2000, 2005 and 2008 $connection = odbc_connect("Driver={SQL Server Native Client 10.0};Server=$server;Database=$database;", $user, $password); // Microsoft Access $connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password); // Microsoft Excel $excelFile = realpath('C:/ExcelData.xls'); $excelDir = dirname($excelFile); $connection = odbc_connect("Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=$excelFile;DefaultDir=$excelDir" , '', ''); ?> ``` ### See Also * For persistent connections: [odbc\_pconnect()](function.odbc-pconnect) - Open a persistent database connection php The Yaf_Exception_TypeError class The Yaf\_Exception\_TypeError class =================================== Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Exception\_TypeError** extends [Yaf\_Exception](class.yaf-exception) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/ ``` public Yaf_Exception::getPrevious(): void ``` } php ReflectionFunctionAbstract::getReturnType ReflectionFunctionAbstract::getReturnType ========================================= (PHP 7, PHP 8) ReflectionFunctionAbstract::getReturnType — Gets the specified return type of a function ### Description ``` public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType ``` Gets the specified return type of a reflected function. ### Parameters This function has no parameters. ### Return Values Returns a [ReflectionType](class.reflectiontype) object if a return type is specified, **`null`** otherwise. ### Examples **Example #1 **ReflectionFunctionAbstract::getReturnType()** example** ``` <?php function to_int($param) : int {     return (int) $param; } $reflection1 = new ReflectionFunction('to_int'); echo $reflection1->getReturnType(); ``` The above example will output: ``` int ``` **Example #2 Usage on built-in functions** ``` <?php $reflection2 = new ReflectionFunction('array_merge'); var_dump($reflection2->getReturnType()); ``` The above example will output: ``` null ``` This is because many internal functions do not have types specified for their parameters or return values. It is therefore best to avoid using this method on built-in functions. ### See Also * [ReflectionFunctionAbstract::hasReturnType()](reflectionfunctionabstract.hasreturntype) - Checks if the function has a specified return type * [ReflectionType::\_\_toString()](reflectiontype.tostring) - To string php Imagick::previousImage Imagick::previousImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::previousImage — Move to the previous image in the object ### Description ``` public Imagick::previousImage(): bool ``` Associates the previous image in an image list with the Imagick object. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. php IntlTimeZone::createEnumeration IntlTimeZone::createEnumeration =============================== intltz\_create\_enumeration =========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::createEnumeration -- intltz\_create\_enumeration — Get an enumeration over time zone IDs associated with the given country or offset ### Description Object-oriented style (method): ``` public static IntlTimeZone::createEnumeration(IntlTimeZone|string|int|float|null $countryOrRawOffset = null): IntlIterator|false ``` Procedural style: ``` intltz_create_enumeration(IntlTimeZone|string|int|float|null $countryOrRawOffset = null): IntlIterator|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `countryOrRawOffset` ### Return Values php posix_getrlimit posix\_getrlimit ================ (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getrlimit — Return info about system resource limits ### Description ``` posix_getrlimit(): array|false ``` **posix\_getrlimit()** returns an array of information about the current resource's soft and hard limits. Each resource has an associated soft and hard limit. The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit. An unprivileged process may only set its soft limit to a value from 0 to the hard limit, and irreversibly lower its hard limit. ### Parameters This function has no parameters. ### Return Values Returns an associative array of elements for each limit that is defined. Each limit has a soft and a hard limit. **List of possible limits returned**| Limit name | Limit description | | --- | --- | | core | The maximum size of the core file. When 0, not core files are created. When core files are larger than this size, they will be truncated at this size. | | totalmem | The maximum size of the memory of the process, in bytes. | | virtualmem | The maximum size of the virtual memory for the process, in bytes. | | data | The maximum size of the data segment for the process, in bytes. | | stack | The maximum size of the process stack, in bytes. | | rss | The maximum number of virtual pages resident in RAM | | maxproc | The maximum number of processes that can be created for the real user ID of the calling process. | | memlock | The maximum number of bytes of memory that may be locked into RAM. | | cpu | The amount of time the process is allowed to use the CPU. | | filesize | The maximum size of the data segment for the process, in bytes. | | openfiles | One more than the maximum number of open file descriptors. | The function returns **`false`** on failure. ### Examples **Example #1 Example use of **posix\_getrlimit()**** ``` <?php $limits = posix_getrlimit(); print_r($limits); ?> ``` The above example will output something similar to: ``` Array ( [soft core] => 0 [hard core] => unlimited [soft data] => unlimited [hard data] => unlimited [soft stack] => 8388608 [hard stack] => unlimited [soft totalmem] => unlimited [hard totalmem] => unlimited [soft rss] => unlimited [hard rss] => unlimited [soft maxproc] => unlimited [hard maxproc] => unlimited [soft memlock] => unlimited [hard memlock] => unlimited [soft cpu] => unlimited [hard cpu] => unlimited [soft filesize] => unlimited [hard filesize] => unlimited [soft openfiles] => 1024 [hard openfiles] => 1024 ) ``` ### See Also * man page GETRLIMIT(2) * [posix\_setrlimit()](function.posix-setrlimit) - Set system resource limits php Ds\Map::remove Ds\Map::remove ============== (PECL ds >= 1.0.0) Ds\Map::remove — Removes and returns a value by key ### Description ``` public Ds\Map::remove(mixed $key, mixed $default = ?): mixed ``` Removes and returns a value by key, or return an optional default value if the key could not be found. > > **Note**: > > > Keys of type object are supported. If an object implements **Ds\Hashable**, equality will be determined by the object's `equals` function. If an object does not implement **Ds\Hashable**, objects must be references to the same instance to be considered equal. > > > > **Note**: > > > You can also use array syntax to access values by key, eg. `$map["key"]`. > > **Caution** Be careful when using array syntax. Scalar keys will be coerced to integers by the engine. For example, `$map["1"]` will attempt to access `int(1)`, while `$map->get("1")` will correctly look up the string key. See [Arrays](language.types.array). ### Parameters `key` The key to remove. `default` The optional default value, returned if the key could not be found. ### Return Values The value that was removed, or the `default` value if provided and the `key` could not be found in the map. ### Errors/Exceptions [OutOfBoundsException](class.outofboundsexception) if the key could not be found and a default value was not provided. ### Examples **Example #1 **Ds\Map::remove()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->remove("a"));      //  1 var_dump($map->remove("e", 10));  // 10 (default used) ?> ``` The above example will output something similar to: ``` int(1) int(10) ``` php cal_info cal\_info ========= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) cal\_info — Returns information about a particular calendar ### Description ``` cal_info(int $calendar = -1): array ``` **cal\_info()** returns information on the specified `calendar`. Calendar information is returned as an array containing the elements `calname`, `calsymbol`, `month`, `abbrevmonth` and `maxdaysinmonth`. The names of the different calendars which can be used as `calendar` are as follows: * 0 or **`CAL_GREGORIAN`** - Gregorian Calendar * 1 or **`CAL_JULIAN`** - Julian Calendar * 2 or **`CAL_JEWISH`** - Jewish Calendar * 3 or **`CAL_FRENCH`** - French Revolutionary Calendar If no `calendar` is specified information on all supported calendars is returned as an array. ### Parameters `calendar` Calendar to return information for. If no calendar is specified information about all calendars is returned. ### Return Values ### Examples **Example #1 **cal\_info()** example** ``` <?php $info = cal_info(0); print_r($info); ?> ``` The above example will output: ``` Array ( [months] => Array ( [1] => January [2] => February [3] => March [4] => April [5] => May [6] => June [7] => July [8] => August [9] => September [10] => October [11] => November [12] => December ) [abbrevmonths] => Array ( [1] => Jan [2] => Feb [3] => Mar [4] => Apr [5] => May [6] => Jun [7] => Jul [8] => Aug [9] => Sep [10] => Oct [11] => Nov [12] => Dec ) [maxdaysinmonth] => 31 [calname] => Gregorian [calsymbol] => CAL_GREGORIAN ) ``` php Yaf_Application::bootstrap Yaf\_Application::bootstrap =========================== (Yaf >=1.0.0) Yaf\_Application::bootstrap — Call bootstrap ### Description ``` public Yaf_Application::bootstrap(Yaf_Bootstrap_Abstract $bootstrap = ?): void ``` Run a Bootstrap, all the methods defined in the Bootstrap and named with prefix "\_init" will be called according to their declaration order, if the parameter bootstrap is not supplied, Yaf will look for a Bootstrap under application.directory. ### Parameters `bootstrap` A [Yaf\_Bootstrap\_Abstract](class.yaf-bootstrap-abstract) instance ### Return Values [Yaf\_Application](class.yaf-application) instance ### Examples **Example #1 **A Bootstrap()**example** ``` <?php /**  * This file should be under the APPLICATION_PATH . "/application/"(which was defined in the config passed to Yaf_Application).  * and named Bootstrap.php,  so the Yaf_Application can find it   */ class Bootstrap extends Yaf_Bootstrap_Abstract {     function _initConfig(Yaf_Dispatcher $dispatcher) {         echo "1st called\n";     }     function _initPlugin($dispatcher) {         echo "2nd called\n";     } } ?> ``` **Example #2 **Yaf\_Application::bootstrap()**example** ``` <?php defined('APPLICATION_PATH') // APPLICATION_PATH will be used in the ini config file     || define('APPLICATION_PATH', __DIR__); $application = new Yaf_Application(APPLICATION_PATH.'/conf/application.ini'); $application->bootstrap(); ?> ``` The above example will output something similar to: ``` 1st called 2nd called ``` ### See Also * [Yaf\_Bootstrap\_Abstract](class.yaf-bootstrap-abstract) php imageftbbox imageftbbox =========== (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) imageftbbox — Give the bounding box of a text using fonts via freetype2 ### Description ``` imageftbbox( float $size, float $angle, string $font_filename, string $string, array $options = [] ): array|false ``` This function calculates and returns the bounding box in pixels for a FreeType text. > > **Note**: > > > Prior to PHP 8.0.0, **imageftbbox()** was an extended variant of [imagettfbbox()](function.imagettfbbox) which additionally supported the `options`. As of PHP 8.0.0, [imagettfbbox()](function.imagettfbbox) is an alias of **imageftbbox()**. > > ### Parameters `size` The font size in points. `angle` Angle in degrees in which `string` will be measured. `font_filename` The name of the TrueType font file (can be a URL). Depending on which version of the GD library that PHP is using, it may attempt to search for files that do not begin with a leading '/' by appending '.ttf' to the filename and searching along a library-defined font path. `string` The string to be measured. `options` **Possible array indexes for `options`**| Key | Type | Meaning | | --- | --- | --- | | `linespacing` | float | Defines drawing linespacing | ### Return Values **imageftbbox()** returns an array with 8 elements representing four points making the bounding box of the text: | | | | --- | --- | | 0 | lower left corner, X position | | 1 | lower left corner, Y position | | 2 | lower right corner, X position | | 3 | lower right corner, Y position | | 4 | upper right corner, X position | | 5 | upper right corner, Y position | | 6 | upper left corner, X position | | 7 | upper left corner, Y position | The points are relative to the *text* regardless of the `angle`, so "upper left" means in the top left-hand corner seeing the text horizontally. On failure, **`false`** is returned. ### Examples **Example #1 **imageftbbox()** example** ``` <?php // Create a 300x150 image $im = imagecreatetruecolor(300, 150); $black = imagecolorallocate($im, 0, 0, 0); $white = imagecolorallocate($im, 255, 255, 255); // Set the background to be white imagefilledrectangle($im, 0, 0, 299, 299, $white); // Path to our font file $font = './arial.ttf'; // First we create our bounding box $bbox = imageftbbox(10, 0, $font, 'The PHP Documentation Group'); // This is our cordinates for X and Y $x = $bbox[0] + (imagesx($im) / 2) - ($bbox[4] / 2) - 5; $y = $bbox[1] + (imagesy($im) / 2) - ($bbox[5] / 2) - 5; imagefttext($im, 10, 0, $x, $y, $black, $font, 'The PHP Documentation Group'); // Output to browser header('Content-Type: image/png'); imagepng($im); imagedestroy($im); ?> ``` ### Notes > **Note**: This function is only available if PHP is compiled with freetype support (**--with-freetype-dir=DIR**) > > ### See Also * [imagefttext()](function.imagefttext) - Write text to the image using fonts using FreeType 2 * [imagettfbbox()](function.imagettfbbox) - Give the bounding box of a text using TrueType fonts
programming_docs
php ReflectionFunctionAbstract::getName ReflectionFunctionAbstract::getName =================================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getName — Gets function name ### Description ``` public ReflectionFunctionAbstract::getName(): string ``` Get the name of the function. ### Parameters This function has no parameters. ### Return Values The name of the function. ### See Also * [ReflectionFunctionAbstract::getExtensionName()](reflectionfunctionabstract.getextensionname) - Gets extension name * [ReflectionFunctionAbstract::isUserDefined()](reflectionfunctionabstract.isuserdefined) - Checks if user defined php SolrQuery::setFacetEnumCacheMinDefaultFrequency SolrQuery::setFacetEnumCacheMinDefaultFrequency =============================================== (PECL solr >= 0.9.2) SolrQuery::setFacetEnumCacheMinDefaultFrequency — Sets the minimum document frequency used for determining term count ### Description ``` public SolrQuery::setFacetEnumCacheMinDefaultFrequency(int $frequency, string $field_override = ?): SolrQuery ``` Sets the minimum document frequency used for determining term count ### Parameters `value` The minimum frequency `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php iconv iconv ===== (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) iconv — Convert a string from one character encoding to another ### Description ``` iconv(string $from_encoding, string $to_encoding, string $string): string|false ``` Converts `string` from `from_encoding` to `to_encoding`. ### Parameters `from_encoding` The current encoding used to interpret `string`. `to_encoding` The desired encoding of the result. If the string `//TRANSLIT` is appended to `to_encoding`, then transliteration is activated. This means that when a character can't be represented in the target charset, it may be approximated through one or several similarly looking characters. If the string `//IGNORE` is appended, characters that cannot be represented in the target charset are silently discarded. Otherwise, **`E_NOTICE`** is generated and the function will return **`false`**. **Caution** If and how `//TRANSLIT` works exactly depends on the system's iconv() implementation (cf. **`ICONV_IMPL`**). Some implementations are known to ignore `//TRANSLIT`, so the conversion is likely to fail for characters which are illegal for the `to_encoding`. `string` The string to be converted. ### Return Values Returns the converted string, or **`false`** on failure. ### Examples **Example #1 **iconv()** example** ``` <?php $text = "This is the Euro symbol '€'."; echo 'Original : ', $text, PHP_EOL; echo 'TRANSLIT : ', iconv("UTF-8", "ISO-8859-1//TRANSLIT", $text), PHP_EOL; echo 'IGNORE   : ', iconv("UTF-8", "ISO-8859-1//IGNORE", $text), PHP_EOL; echo 'Plain    : ', iconv("UTF-8", "ISO-8859-1", $text), PHP_EOL; ?> ``` The above example will output something similar to: ``` Original : This is the Euro symbol '€'. TRANSLIT : This is the Euro symbol 'EUR'. IGNORE : This is the Euro symbol ''. Plain : Notice: iconv(): Detected an illegal character in input string in .\iconv-example.php on line 7 ``` ### Notes > > **Note**: > > > The character encodings and options available depend on the installed implementation of iconv. If the argument to `from_encoding` or `to_encoding` is not supported on the current system, **`false`** will be returned. > > ### See Also * [mb\_convert\_encoding()](function.mb-convert-encoding) - Convert a string from one character encoding to another * [UConverter::transcode()](uconverter.transcode) - Convert a string from one character encoding to another php MessageFormatter::parseMessage MessageFormatter::parseMessage ============================== msgfmt\_parse\_message ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) MessageFormatter::parseMessage -- msgfmt\_parse\_message — Quick parse input string ### Description Object-oriented style ``` public static MessageFormatter::parseMessage(string $locale, string $pattern, string $message): array|false ``` Procedural style ``` msgfmt_parse_message(string $locale, string $pattern, string $message): array|false ``` Parses input string without explicitly creating the formatter object. Use this function when the format operation is done only once and does not need any parameters or state to be kept. ### Parameters `locale` The locale to use for parsing locale-dependent parts `pattern` The pattern with which to parse the `message`. `message` The string to parse, conforming to the `pattern`. ### Return Values An array containing items extracted, or **`false`** on error ### Examples **Example #1 **msgfmt\_parse\_message()** example** ``` <?php $fmt = msgfmt_parse_message('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",                             "4,560 monkeys on 123 trees make 37.073 monkeys per tree"); var_export($fmt); $fmt = msgfmt_parse_message('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",                              "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum"); var_export($fmt); ?> ``` **Example #2 OO example** ``` <?php $fmt = MessageFormatter::parseMessage('en_US', "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree",                             "4,560 monkeys on 123 trees make 37.073 monkeys per tree"); var_export($fmt); $fmt = MessageFormatter::parseMessage('de', "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum",                              "4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum"); var_export($fmt); ?> ``` The above example will output: ``` array ( 0 => 4560, 1 => 123, 2 => 37.073, ) array ( 0 => 4560, 1 => 123, 2 => 37.073, ) ``` ### See Also * [msgfmt\_create()](messageformatter.create) - Constructs a new Message Formatter * [msgfmt\_format\_message()](messageformatter.formatmessage) - Quick format message * [msgfmt\_parse()](messageformatter.parse) - Parse input string according to pattern php imap_fetchstructure imap\_fetchstructure ==================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_fetchstructure — Read the structure of a particular message ### Description ``` imap_fetchstructure(IMAP\Connection $imap, int $message_num, int $flags = 0): stdClass|false ``` Fetches all the structured information for a given message. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_num` The message number `flags` This optional parameter only has a single option, **`FT_UID`**, which tells the function to treat the `message_num` argument as a `UID`. ### Return Values Returns an object with properties listed in the table below, or **`false`** on failure. **Returned Object for **imap\_fetchstructure()**** | type | Primary body type | | encoding | Body transfer encoding | | ifsubtype | **`true`** if there is a subtype string | | subtype | MIME subtype | | ifdescription | **`true`** if there is a description string | | description | Content description string | | ifid | **`true`** if there is an identification string | | id | Identification string | | lines | Number of lines | | bytes | Number of bytes | | ifdisposition | **`true`** if there is a disposition string | | disposition | Disposition string | | ifdparameters | **`true`** if the dparameters array exists | | dparameters | An array of objects where each object has an `"attribute"` and a `"value"` property corresponding to the parameters on the `Content-disposition` MIME header. | | ifparameters | **`true`** if the parameters array exists | | parameters | An array of objects where each object has an `"attribute"` and a `"value"` property. | | parts | An array of objects identical in structure to the top-level object, each of which corresponds to a MIME body part. | **Primary body type (value may vary with used library, use of constants is recommended)**| Value | Type | Constant | | --- | --- | --- | | 0 | text | TYPETEXT | | 1 | multipart | TYPEMULTIPART | | 2 | message | TYPEMESSAGE | | 3 | application | TYPEAPPLICATION | | 4 | audio | TYPEAUDIO | | 5 | image | TYPEIMAGE | | 6 | video | TYPEVIDEO | | 7 | model | TYPEMODEL | | 8 | other | TYPEOTHER | **Transfer encodings (value may vary with used library, use of constants is recommended)**| Value | Type | Constant | | --- | --- | --- | | 0 | 7bit | ENC7BIT | | 1 | 8bit | ENC8BIT | | 2 | Binary | ENCBINARY | | 3 | Base64 | ENCBASE64 | | 4 | Quoted-Printable | ENCQUOTEDPRINTABLE | | 5 | other | ENCOTHER | ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_fetchbody()](function.imap-fetchbody) - Fetch a particular section of the body of the message * [imap\_bodystruct()](function.imap-bodystruct) - Read the structure of a specified body section of a specific message php socket_import_stream socket\_import\_stream ====================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) socket\_import\_stream — Import a stream ### Description ``` socket_import_stream(resource $stream): Socket|false ``` Imports a stream that encapsulates a socket into a socket extension resource. ### Parameters `stream` The stream resource to import. ### Return Values Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [Socket](class.socket) instance now; previously, a resource was returned. | ### Examples **Example #1 **socket\_import\_stream()** example** ``` <?php $stream = stream_socket_server("udp://0.0.0.0:58380", $errno, $errstr, STREAM_SERVER_BIND);  $sock   = socket_import_stream($stream); ?> ``` ### See Also * [stream\_socket\_server()](function.stream-socket-server) - Create an Internet or Unix domain server socket php Yaf_Session::offsetGet Yaf\_Session::offsetGet ======================= (Yaf >=1.0.0) Yaf\_Session::offsetGet — The offsetGet purpose ### Description ``` public Yaf_Session::offsetGet(string $name): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php EventListener::__construct EventListener::\_\_construct ============================ (PECL event >= 1.2.6-beta) EventListener::\_\_construct — Creates new connection listener associated with an event base ### Description ``` public EventListener::__construct( EventBase $base , callable $cb , mixed $data , int $flags , int $backlog , mixed $target ) ``` Creates new connection listener associated with an event base. ### Parameters `base` Associated event base. `cb` A [callable](language.types.callable) that will be invoked when new connection received. `data` Custom user data attached to `cb` . `flags` Bit mask of `EventListener::OPT_*` constants. See [EventListener constants](class.eventlistener#eventlistener.constants) . `backlog` Controls the maximum number of pending connections that the network stack should allow to wait in a not-yet-accepted state at any time; see documentation for your system’s `listen` function for more details. If `backlog` is negative, Libevent tries to pick a good value for the `backlog` ; if it is zero, Event assumes that `listen` is already called on the socket( `target` ) `target` May be string, socket resource, or a stream associated with a socket. In case if `target` is a string, the string will be parsed as network address. It will be interpreted as a UNIX domain socket path, if prefixed with `'unix:'` , e.g. `'unix:/tmp/my.sock'` . ### Return Values Returns [EventListener](class.eventlistener) object representing the event connection listener. ### Changelog | Version | Description | | --- | --- | | PECL event 1.5.0 | UNIX domain sockets' support added. | ### Examples **Example #1 **EventListener::\_\_construct()** example** ``` <?php /*  * Simple echo server based on libevent's connection listener.  *  * Usage:  * 1) In one terminal window run:  *  * $ php listener.php 9881  *  * 2) In another terminal window open up connection, e.g.:  *  * $ nc 127.0.0.1 9881  *  * 3) start typing. The server should repeat the input.  */ class MyListenerConnection {     private $bev, $base;     public function __destruct() {         $this->bev->free();     }     public function __construct($base, $fd) {         $this->base = $base;         $this->bev = new EventBufferEvent($base, $fd, EventBufferEvent::OPT_CLOSE_ON_FREE);         $this->bev->setCallbacks(array($this, "echoReadCallback"), NULL,             array($this, "echoEventCallback"), NULL);         if (!$this->bev->enable(Event::READ)) {             echo "Failed to enable READ\n";             return;         }     }     public function echoReadCallback($bev, $ctx) {         // Copy all the data from the input buffer to the output buffer                  // Variant #1         $bev->output->addBuffer($bev->input);         /* Variant #2 */         /*         $input    = $bev->getInput();         $output = $bev->getOutput();         $output->addBuffer($input);         */     }     public function echoEventCallback($bev, $events, $ctx) {         if ($events & EventBufferEvent::ERROR) {             echo "Error from bufferevent\n";         }         if ($events & (EventBufferEvent::EOF | EventBufferEvent::ERROR)) {             //$bev->free();             $this->__destruct();         }     } } class MyListener {     public $base,         $listener,         $socket;     private $conn = array();     public function __destruct() {         foreach ($this->conn as &$c) $c = NULL;     }     public function __construct($port) {         $this->base = new EventBase();         if (!$this->base) {             echo "Couldn't open event base";             exit(1);         }         // Variant #1         /*         $this->socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);         if (!socket_bind($this->socket, '0.0.0.0', $port)) {             echo "Unable to bind socket\n";             exit(1);         }         $this->listener = new EventListener($this->base,             array($this, "acceptConnCallback"), $this->base,             EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE,             -1, $this->socket);          */         // Variant #2          $this->listener = new EventListener($this->base,              array($this, "acceptConnCallback"), $this->base,              EventListener::OPT_CLOSE_ON_FREE | EventListener::OPT_REUSEABLE, -1,              "0.0.0.0:$port");         if (!$this->listener) {             echo "Couldn't create listener";             exit(1);         }         $this->listener->setErrorCallback(array($this, "accept_error_cb"));     }     public function dispatch() {         $this->base->dispatch();     }     // This callback is invoked when there is data to read on $bev     public function acceptConnCallback($listener, $fd, $address, $ctx) {         // We got a new connection! Set up a bufferevent for it. */         $base = $this->base;         $this->conn[] = new MyListenerConnection($base, $fd);     }     public function accept_error_cb($listener, $ctx) {         $base = $this->base;         fprintf(STDERR, "Got an error %d (%s) on the listener. "             ."Shutting down.\n",             EventUtil::getLastSocketErrno(),             EventUtil::getLastSocketError());         $base->exit(NULL);     } } $port = 9808; if ($argc > 1) {     $port = (int) $argv[1]; } if ($port <= 0 || $port > 65535) {     exit("Invalid port"); } $l = new MyListener($port); $l->dispatch(); ?> ``` php EventHttpConnection::setTimeout EventHttpConnection::setTimeout =============================== (PECL event >= 1.2.6-beta) EventHttpConnection::setTimeout — Sets the timeout for the connection ### Description ``` public EventHttpConnection::setTimeout( int $timeout ): void ``` Sets the timeout for the connection ### Parameters `timeout` Timeout in seconds. ### Return Values No value is returned. php enchant_dict_quick_check enchant\_dict\_quick\_check =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant:0.2.0-1.0.1) enchant\_dict\_quick\_check — Check the word is correctly spelled and provide suggestions ### Description ``` enchant_dict_quick_check(EnchantDictionary $dictionary, string $word, array &$suggestions = null): bool ``` If the word is correctly spelled return **`true`**, otherwise return **`false`**, if suggestions variable is provided, fill it with spelling alternatives. ### Parameters `dictionary` An Enchant dictionary returned by [enchant\_broker\_request\_dict()](function.enchant-broker-request-dict) or [enchant\_broker\_request\_pwl\_dict()](function.enchant-broker-request-pwl-dict). `word` The word to check `suggestions` If the word is not correctly spelled, this variable will contain an array of suggestions. ### Return Values Returns **`true`** if the word is correctly spelled or **`false`** ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dictionary` expects an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was expected. | ### Examples **Example #1 A **enchant\_dict\_quick\_check()** example** ``` <?php $tag = 'en_US'; $r = enchant_broker_init(); if (enchant_broker_dict_exists($r,$tag)) {     $d = enchant_broker_request_dict($r, $tag);     enchant_dict_quick_check($d, 'soong', $suggs);     print_r($suggs); } ?> ``` The above example will output something similar to: ``` Array ( [0] => song [1] => snog [2] => soon [3] => Sang [4] => Sung [5] => sang [6] => sung [7] => sponge [8] => spongy [9] => snag [10] => snug [11] => sonic [12] => sing [13] => songs [14] => Son [15] => Sonja [16] => Synge [17] => son [18] => Sejong [19] => sarong [20] => sooner [21] => Sony [22] => sown [23] => scone [24] => song's ) ``` ### See Also * [enchant\_dict\_check()](function.enchant-dict-check) - Check whether a word is correctly spelled or not * [enchant\_dict\_suggest()](function.enchant-dict-suggest) - Will return a list of values if any of those pre-conditions are not met php EventHttpRequest::getConnection EventHttpRequest::getConnection =============================== (PECL event >= 1.8.0) EventHttpRequest::getConnection — Returns EventHttpConnection object ### Description ``` public EventHttpRequest::closeConnection(): EventHttpConnection ``` Returns [EventHttpConnection](class.eventhttpconnection) object which represents HTTP connection associated with the request. **Warning** Libevent API allows HTTP request objects to be not bound to any HTTP connection. Therefore we can't unambiguously associate [EventHttpRequest](class.eventhttprequest) with [EventHttpConnection](class.eventhttpconnection) . Thus, we construct [EventHttpConnection](class.eventhttpconnection) object on-the-fly. Having no information about the event base, DNS base and connection-close callback, we just leave these fields unset. **EventHttpRequest::getConnection()** method is usually useful when we need to set up a callback on connection close. See [EventHttpConnection::setCloseCallback()](eventhttpconnection.setclosecallback) . ### Parameters This function has no parameters. ### Return Values Returns [EventHttpConnection](class.eventhttpconnection) object. ### See Also * [EventHttpConnection::setCloseCallback()](eventhttpconnection.setclosecallback) - Set callback for connection close * [EventHttpRequest::getBufferEvent()](eventhttprequest.getbufferevent) - Returns EventBufferEvent object
programming_docs
php GmagickDraw::getfillopacity GmagickDraw::getfillopacity =========================== (PECL gmagick >= Unknown) GmagickDraw::getfillopacity — Returns the opacity used when drawing ### Description ``` public GmagickDraw::getfillopacity(): float ``` Returns the opacity used when drawing ### Parameters This function has no parameters. ### Return Values Returns the opacity used when drawing using the fill color or fill texture. Fully opaque is 1.0. php Imagick::morphology Imagick::morphology =================== (PECL imagick 3 >= 3.3.0) Imagick::morphology — Description ### Description ``` public Imagick::morphology( int $morphologyMethod, int $iterations, ImagickKernel $ImagickKernel, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` Applies a user supplied kernel to the image according to the given morphology method. ### Parameters `morphologyMethod` Which morphology method to use one of the \Imagick::MORPHOLOGY\_\* constants. `iterations` The number of iteration to apply the morphology function. A value of -1 means loop until no change found. How this is applied may depend on the morphology method. Typically this is a value of 1. `ImagickKernel` `channel` ### Return Values Returns **`true`** on success. ### Examples **Example #1 Convolve **Imagick::morphology()**** ``` <?php         $imagick = $this->getCharacter();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_GAUSSIAN, "5,1");         $imagick->morphology(\Imagick::MORPHOLOGY_CONVOLVE, 2, $kernel);         header("Content-Type: image/png");         echo $imagick->getImageBlob(); ?> ``` **Example #2 Correlate **Imagick::morphology()**** ``` <?php         // Top-left pixel must be black         // Bottom right pixel must be white         // We don't care about the rest.                  $imagick = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromMatrix(self::$correlateMatrix, [2, 2]);         $imagick->morphology(\Imagick::MORPHOLOGY_CORRELATE, 1, $kernel);         header("Content-Type: image/png");         echo $imagick->getImageBlob(); ?> ``` **Example #3 Erode **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_ERODE, 2, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #4 Erode Intensity **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacter();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");         $canvas->morphology(\Imagick::MORPHOLOGY_ERODE_INTENSITY, 2, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #5 Dilate **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_DILATE, 4, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #6 Dilate intensity **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacter();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "1");         $canvas->morphology(\Imagick::MORPHOLOGY_DILATE_INTENSITY, 4, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #7 Distance with Chebyshev kernel **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CHEBYSHEV, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);         $canvas->autoLevelImage();         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #8 Distance with Manhattan kernel **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_MANHATTAN, "5");         $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);         $canvas->autoLevelImage();         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #9 Distance with ocatagonal kernel **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGONAL, "5");         $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);         $canvas->autoLevelImage();         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #10 Distance with Euclidean kernel **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_EUCLIDEAN, "4");         $canvas->morphology(\Imagick::MORPHOLOGY_DISTANCE, 3, $kernel);         $canvas->autoLevelImage();         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #11 Edge **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_EDGE, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #12 Open **Imagick::morphology()**** ``` <?php         // As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");         $canvas->morphology(\Imagick::MORPHOLOGY_OPEN, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #13 Open intensity **Imagick::morphology()**** ``` <?php         // As a result you will see that 'Open' smoothed the outline, by rounding off any sharp points, and remove any parts that is smaller than the shape used. It will also disconnect or 'open' any thin bridges.         $canvas = $this->getCharacter();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");         $canvas->morphology(\Imagick::MORPHOLOGY_OPEN_INTENSITY, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #14 Close **Imagick::morphology()**** ``` <?php         //The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");         $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #15 Close Intensity **Imagick::morphology()**** ``` <?php         //The basic use of the 'Close' method is to reduce or remove any 'holes' or 'gaps' about the size of the kernel 'Structure Element'. That is 'close' parts of the background that are about that size.         $canvas = $this->getCharacter();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "6");         $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE_INTENSITY, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #16 Smooth **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_SMOOTH, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #17 Edge in **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_EDGE_IN, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #18 Edge out **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_OCTAGON, "3");         $canvas->morphology(\Imagick::MORPHOLOGY_EDGE_OUT, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #19 The 'TopHat' method, or more specifically 'White Top Hat', returns the pixels that were removed by a Opening of the shape, that is the pixels that were removed to round off the points, and the connecting bridged between shapes. **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");         $canvas->morphology(\Imagick::MORPHOLOGY_TOP_HAT, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #20 The 'BottomHat' method, also known as 'Black TopHat' is the pixels that a Closing of the shape adds to the image. That is the pixels that were used to fill in the 'holes', 'gaps', and 'bridges'. **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "5");         $canvas->morphology(\Imagick::MORPHOLOGY_BOTTOM_HAT, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #21 Hit and Miss **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         //This finds all the pixels with 3 pixels of the right edge         $matrix = [[1, false, false, 0]];         $kernel = \ImagickKernel::fromMatrix(             $matrix,             [0, 0]         );         $canvas->morphology(\Imagick::MORPHOLOGY_HIT_AND_MISS, 1, $kernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #22 Thinning **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);         $rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);         $leftEdgeKernel->addKernel($rightEdgeKernel);                  $canvas->morphology(\Imagick::MORPHOLOGY_THINNING, 3, $leftEdgeKernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #23 Thicken **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $leftEdgeKernel = \ImagickKernel::fromMatrix([[0, 1]], [1, 0]);         $rightEdgeKernel = \ImagickKernel::fromMatrix([[1, 0]], [0, 0]);         $leftEdgeKernel->addKernel($rightEdgeKernel);         $canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, 3, $leftEdgeKernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #24 Thick to generate a convex hull **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $diamondKernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DIAMOND, "1");         $convexKernel =  \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_CONVEX_HULL, "");         // The thicken morphology doesn't handle small gaps. We close them         // with the close morphology.         $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);         $canvas->morphology(\Imagick::MORPHOLOGY_THICKEN, -1, $convexKernel);         $canvas->morphology(\Imagick::MORPHOLOGY_CLOSE, 1, $diamondKernel);         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #25 Iterative morphology **Imagick::morphology()**** ``` <?php         $canvas = $this->getCharacterOutline();         $kernel = \ImagickKernel::fromBuiltIn(\Imagick::KERNEL_DISK, "2");                 $canvas->morphology(\Imagick::MORPHOLOGY_ITERATIVE, 3, $kernel);         $canvas->autoLevelImage();         header("Content-Type: image/png");         echo $canvas->getImageBlob(); ?> ``` **Example #26 Helper function to get an image silhouette **Imagick::morphology()**** ``` <?php function getCharacterOutline() {     $imagick = new \Imagick(realpath("./images/character.png"));     $character = new \Imagick();     $character->newPseudoImage(         $imagick->getImageWidth(),         $imagick->getImageHeight(),         "canvas:white"     );     $canvas = new \Imagick();     $canvas->newPseudoImage(         $imagick->getImageWidth(),         $imagick->getImageHeight(),         "canvas:black"     );     $character->compositeimage(         $imagick,         \Imagick::COMPOSITE_COPYOPACITY,         0, 0     );     $canvas->compositeimage(         $character,         \Imagick::COMPOSITE_ATOP,         0, 0     );     $canvas->setFormat('png');     return $canvas; } ?> ``` php MultipleIterator::key MultipleIterator::key ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) MultipleIterator::key — Gets the registered iterator instances ### Description ``` public MultipleIterator::key(): array ``` Get the registered iterator instances key() result. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values An array of all registered iterator instances. ### Errors/Exceptions A [RuntimeException](class.runtimeexception) if the iterator is invalid (as of PHP 8.1.0), or mode **`MIT_NEED_ALL`** is set, and at least one attached iterator is not valid. Calling this method from [foreach](control-structures.foreach) triggers warning "Illegal type returned". ### Changelog | Version | Description | | --- | --- | | 8.1.0 | A [RuntimeException](class.runtimeexception) is now thrown if **MultipleIterator::key()** is called on an invalid iterator. Previously, **`false`** was returned. | ### See Also * [MultipleIterator::current()](multipleiterator.current) - Gets the registered iterator instances php The ReflectionFiber class The ReflectionFiber class ========================= Introduction ------------ (PHP 8 >= 8.1.0) Class synopsis -------------- final class **ReflectionFiber** { /\* Methods \*/ public [\_\_construct](reflectionfiber.construct)([Fiber](class.fiber) `$fiber`) ``` public getCallable(): callable ``` ``` public getExecutingFile(): string ``` ``` public getExecutingLine(): int ``` ``` public getFiber(): Fiber ``` ``` public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array ``` } Table of Contents ----------------- * [ReflectionFiber::\_\_construct](reflectionfiber.construct) — Constructs a ReflectionFiber object * [ReflectionFiber::getCallable](reflectionfiber.getcallable) — Gets the callable used to create the Fiber * [ReflectionFiber::getExecutingFile](reflectionfiber.getexecutingfile) — Get the file name of the current execution point * [ReflectionFiber::getExecutingLine](reflectionfiber.getexecutingline) — Get the line number of the current execution point * [ReflectionFiber::getFiber](reflectionfiber.getfiber) — Get the reflected Fiber instance * [ReflectionFiber::getTrace](reflectionfiber.gettrace) — Get the backtrace of the current execution point php The SolrServerException class The SolrServerException class ============================= Introduction ------------ (PECL Solr >= 1.1.0, >=2.0.0) An exception thrown when there is an error produced by the Solr Server itself. Class synopsis -------------- class **SolrServerException** extends [SolrException](class.solrexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; protected int [$sourceline](class.solrexception#solrexception.props.sourceline); protected string [$sourcefile](class.solrexception#solrexception.props.sourcefile); protected string [$zif\_name](class.solrexception#solrexception.props.zif-name); /\* Methods \*/ ``` public getInternalInfo(): array ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` ``` public SolrException::getInternalInfo(): array ``` } Table of Contents ----------------- * [SolrServerException::getInternalInfo](solrserverexception.getinternalinfo) — Returns internal information where the Exception was thrown php IntlChar::chr IntlChar::chr ============= (PHP 7, PHP 8) IntlChar::chr — Return Unicode character by code point value ### Description ``` public static IntlChar::chr(int|string $codepoint): ?string ``` Returns a string containing the character specified by the Unicode code point value. This function complements [IntlChar::ord()](intlchar.ord). ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values A string containing the single character specified by the Unicode code point value, or **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php $values = ["A", 63, 123, 9731]; foreach ($values as $value) {     var_dump(IntlChar::chr($value)); } ?> ``` The above example will output: ``` string(1) "A" string(1) "?" string(1) "{" string(3) "☃" ``` ### See Also * [IntlChar::ord()](intlchar.ord) - Return Unicode code point value of character * [mb\_chr()](function.mb-chr) - Return character by Unicode code point value * [chr()](function.chr) - Generate a single-byte string from a number php ssh2_publickey_remove ssh2\_publickey\_remove ======================= (PECL ssh2 >= 0.10) ssh2\_publickey\_remove — Remove an authorized publickey ### Description ``` ssh2_publickey_remove(resource $pkey, string $algoname, string $blob): bool ``` Removes an authorized publickey. ### Parameters `pkey` Publickey Subsystem Resource `algoname` Publickey algorithm (e.g.): ssh-dss, ssh-rsa `blob` Publickey blob as raw binary data ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes > **Note**: The public key subsystem is used for managing public keys on a server to which the client is *already* authenticated. To authenticate to a remote system using public key authentication, use the [ssh2\_auth\_pubkey\_file()](function.ssh2-auth-pubkey-file) function instead. > > ### See Also * [ssh2\_publickey\_init()](function.ssh2-publickey-init) - Initialize Publickey subsystem * [ssh2\_publickey\_add()](function.ssh2-publickey-add) - Add an authorized publickey * [ssh2\_publickey\_list()](function.ssh2-publickey-list) - List currently authorized publickeys
programming_docs
php IntlCalendar::before IntlCalendar::before ==================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::before — Whether this objectʼs time is before that of the passed object ### Description Object-oriented style ``` public IntlCalendar::before(IntlCalendar $other): bool ``` Procedural style ``` intlcal_before(IntlCalendar $calendar, IntlCalendar $other): bool ``` Returns whether this objectʼs time precedes the argumentʼs time. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `other` The calendar whose time will be checked against the primary objectʼs time. ### Return Values Returns **`true`** if this objectʼs current time is before that of the `calendar` argumentʼs time. Returns **`false`** otherwise. On failure **`false`** is also returned. To detect error conditions use [intl\_get\_error\_code()](function.intl-get-error-code), or set up Intl to throw [exceptions](https://www.php.net/manual/en/intl.configuration.php#ini.intl.use-exceptions). php DateTimeZone::getLocation DateTimeZone::getLocation ========================= timezone\_location\_get ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) DateTimeZone::getLocation -- timezone\_location\_get — Returns location information for a timezone ### Description Object-oriented style ``` public DateTimeZone::getLocation(): array|false ``` Procedural style ``` timezone_location_get(DateTimeZone $object): array|false ``` Returns location information for a timezone, including country code, latitude/longitude and comments. ### Parameters `object` Procedural style only: A [DateTimeZone](class.datetimezone) object returned by [timezone\_open()](function.timezone-open) ### Return Values Array containing location information about timezone or **`false`** on failure. ### Examples **Example #1 **DateTimeZone::getLocation()** example** ``` <?php $tz = new DateTimeZone("Europe/Prague"); print_r($tz->getLocation()); print_r(timezone_location_get($tz)); ?> ``` The above example will output: ``` Array ( [country_code] => CZ [latitude] => 50.08333 [longitude] => 14.43333 [comments] => ) Array ( [country_code] => CZ [latitude] => 50.08333 [longitude] => 14.43333 [comments] => ) ``` ### See Also * [DateTimeZone::listIdentifiers()](datetimezone.listidentifiers) - Returns a numerically indexed array containing all defined timezone identifiers to get a full or partial list of all supported timezone identifiers php SVM::setOptions SVM::setOptions =============== (PECL svm >= 0.1.0) SVM::setOptions — Set training parameters ### Description ``` public SVM::setOptions(array $params): bool ``` Set one or more training parameters. ### Parameters `params` An array of training parameters, keyed on the SVM constants. ### Return Values Return true on success, throws SVMException on error. php Imagick::linearStretchImage Imagick::linearStretchImage =========================== (PECL imagick 2, PECL imagick 3) Imagick::linearStretchImage — Stretches with saturation the image intensity ### Description ``` public Imagick::linearStretchImage(float $blackPoint, float $whitePoint): bool ``` Stretches with saturation the image intensity. ### Parameters `blackPoint` The image black point `whitePoint` The image white point ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::linearStretchImage()**** ``` <?php function linearStretchImage($imagePath, $blackThreshold, $whiteThreshold) {     $imagick = new \Imagick(realpath($imagePath));     $pixels = $imagick->getImageWidth() * $imagick->getImageHeight();     $imagick->linearStretchImage($blackThreshold * $pixels, $whiteThreshold * $pixels);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php imagescale imagescale ========== (PHP 5 >= 5.5.0, PHP 7, PHP 8) imagescale — Scale an image using the given new width and height ### Description ``` imagescale( GdImage $image, int $width, int $height = -1, int $mode = IMG_BILINEAR_FIXED ): GdImage|false ``` **imagescale()** scales an image using the given interpolation algorithm. > > **Note**: > > > Unlike many of other image functions, **imagescale()** does not modify the passed `image`; instead, a *new* image is returned. > > ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `width` The width to scale the image to. `height` The height to scale the image to. If omitted or negative, the aspect ratio will be preserved. `mode` One of **`IMG_NEAREST_NEIGHBOUR`**, **`IMG_BILINEAR_FIXED`**, **`IMG_BICUBIC`**, **`IMG_BICUBIC_FIXED`** or anything else (will use two pass). > **Note**: **`IMG_WEIGHTED4`** is not yet supported. > > ### Return Values Return the scaled image object on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### See Also * [imagecopyresized()](function.imagecopyresized) - Copy and resize part of an image * [imagecopyresampled()](function.imagecopyresampled) - Copy and resize part of an image with resampling php closelog closelog ======== (PHP 4, PHP 5, PHP 7, PHP 8) closelog — Close connection to system logger ### Description ``` closelog(): bool ``` **closelog()** closes the descriptor being used to write to the system logger. The use of **closelog()** is optional. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [syslog()](function.syslog) - Generate a system log message * [openlog()](function.openlog) - Open connection to system logger php sodium_crypto_scalarmult_ristretto255_base sodium\_crypto\_scalarmult\_ristretto255\_base ============================================== (PHP 8 >= 8.1.1) sodium\_crypto\_scalarmult\_ristretto255\_base — Calculates the public key from a secret key ### Description ``` sodium_crypto_scalarmult_ristretto255_base(string $n): string ``` Given a secret key, calculates the corresponding public key. Available as of libsodium 1.0.18. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `n` A secret key. ### Return Values Returns a 32-byte random string. ### See Also * [sodium\_crypto\_scalarmult\_ristretto255()](function.sodium-crypto-scalarmult-ristretto255) - Computes a shared secret php Imagick::getImageUnits Imagick::getImageUnits ====================== (PECL imagick 2, PECL imagick 3) Imagick::getImageUnits — Gets the image units of resolution ### Description ``` public Imagick::getImageUnits(): int ``` Gets the image units of resolution. ### Parameters This function has no parameters. ### Return Values Returns the image units of resolution. ### Errors/Exceptions Throws ImagickException on error. php GearmanJob::sendFail GearmanJob::sendFail ==================== (PECL gearman >= 0.6.0) GearmanJob::sendFail — Send fail status ### Description ``` public GearmanJob::sendFail(): bool ``` Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception). ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::sendException()](gearmanjob.sendexception) - Send exception for running job (exception) * [GearmanJob::setReturn()](gearmanjob.setreturn) - Set a return value * [GearmanJob::sendStatus()](gearmanjob.sendstatus) - Send status * [GearmanJob::sendWarning()](gearmanjob.sendwarning) - Send a warning php The SolrDocument class The SolrDocument class ====================== Introduction ------------ (PECL solr >= 0.9.2) Represents a Solr document retrieved from a query response. Class synopsis -------------- final class **SolrDocument** implements [ArrayAccess](class.arrayaccess), [Iterator](class.iterator), [Serializable](class.serializable) { /\* Constants \*/ const int [SORT\_DEFAULT](class.solrdocument#solrdocument.constants.sort-default) = 1; const int [SORT\_ASC](class.solrdocument#solrdocument.constants.sort-asc) = 1; const int [SORT\_DESC](class.solrdocument#solrdocument.constants.sort-desc) = 2; const int [SORT\_FIELD\_NAME](class.solrdocument#solrdocument.constants.sort-field-name) = 1; const int [SORT\_FIELD\_VALUE\_COUNT](class.solrdocument#solrdocument.constants.sort-field-value-count) = 2; const int [SORT\_FIELD\_BOOST\_VALUE](class.solrdocument#solrdocument.constants.sort-field-boost-value) = 4; /\* Methods \*/ public [\_\_construct](solrdocument.construct)() ``` public addField(string $fieldName, string $fieldValue): bool ``` ``` public clear(): bool ``` ``` public __clone(): void ``` ``` public current(): SolrDocumentField ``` ``` public deleteField(string $fieldName): bool ``` ``` public fieldExists(string $fieldName): bool ``` ``` public __get(string $fieldName): SolrDocumentField ``` ``` public getChildDocuments(): array ``` ``` public getChildDocumentsCount(): int ``` ``` public getField(string $fieldName): SolrDocumentField ``` ``` public getFieldCount(): int ``` ``` public getFieldNames(): array ``` ``` public getInputDocument(): SolrInputDocument ``` ``` public hasChildDocuments(): bool ``` ``` public __isset(string $fieldName): bool ``` ``` public key(): string ``` ``` public merge(SolrDocument $sourceDoc, bool $overwrite = true): bool ``` ``` public next(): void ``` ``` public offsetExists(string $fieldName): bool ``` ``` public offsetGet(string $fieldName): SolrDocumentField ``` ``` public offsetSet(string $fieldName, string $fieldValue): void ``` ``` public offsetUnset(string $fieldName): void ``` ``` public reset(): bool ``` ``` public rewind(): void ``` ``` public serialize(): string ``` ``` public __set(string $fieldName, string $fieldValue): bool ``` ``` public sort(int $sortOrderBy, int $sortDirection = SolrDocument::SORT_ASC): bool ``` ``` public toArray(): array ``` ``` public unserialize(string $serialized): void ``` ``` public __unset(string $fieldName): bool ``` ``` public valid(): bool ``` public [\_\_destruct](solrdocument.destruct)() } Predefined Constants -------------------- **`SolrDocument::SORT_DEFAULT`** Default mode for sorting fields within the document. **`SolrDocument::SORT_ASC`** Sorts the fields in ascending order **`SolrDocument::SORT_DESC`** Sorts the fields in descending order **`SolrDocument::SORT_FIELD_NAME`** Sorts the fields by field name. **`SolrDocument::SORT_FIELD_VALUE_COUNT`** Sorts the fields by number of values in each field. **`SolrDocument::SORT_FIELD_BOOST_VALUE`** Sorts the fields by thier boost values. Table of Contents ----------------- * [SolrDocument::addField](solrdocument.addfield) — Adds a field to the document * [SolrDocument::clear](solrdocument.clear) — Drops all the fields in the document * [SolrDocument::\_\_clone](solrdocument.clone) — Creates a copy of a SolrDocument object * [SolrDocument::\_\_construct](solrdocument.construct) — Constructor * [SolrDocument::current](solrdocument.current) — Retrieves the current field * [SolrDocument::deleteField](solrdocument.deletefield) — Removes a field from the document * [SolrDocument::\_\_destruct](solrdocument.destruct) — Destructor * [SolrDocument::fieldExists](solrdocument.fieldexists) — Checks if a field exists in the document * [SolrDocument::\_\_get](solrdocument.get) — Access the field as a property * [SolrDocument::getChildDocuments](solrdocument.getchilddocuments) — Returns an array of child documents (SolrDocument) * [SolrDocument::getChildDocumentsCount](solrdocument.getchilddocumentscount) — Returns the number of child documents * [SolrDocument::getField](solrdocument.getfield) — Retrieves a field by name * [SolrDocument::getFieldCount](solrdocument.getfieldcount) — Returns the number of fields in this document * [SolrDocument::getFieldNames](solrdocument.getfieldnames) — Returns an array of fields names in the document * [SolrDocument::getInputDocument](solrdocument.getinputdocument) — Returns a SolrInputDocument equivalent of the object * [SolrDocument::hasChildDocuments](solrdocument.haschilddocuments) — Checks whether the document has any child documents * [SolrDocument::\_\_isset](solrdocument.isset) — Checks if a field exists * [SolrDocument::key](solrdocument.key) — Retrieves the current key * [SolrDocument::merge](solrdocument.merge) — Merges source to the current SolrDocument * [SolrDocument::next](solrdocument.next) — Moves the internal pointer to the next field * [SolrDocument::offsetExists](solrdocument.offsetexists) — Checks if a particular field exists * [SolrDocument::offsetGet](solrdocument.offsetget) — Retrieves a field * [SolrDocument::offsetSet](solrdocument.offsetset) — Adds a field to the document * [SolrDocument::offsetUnset](solrdocument.offsetunset) — Removes a field * [SolrDocument::reset](solrdocument.reset) — Alias of SolrDocument::clear * [SolrDocument::rewind](solrdocument.rewind) — Resets the internal pointer to the beginning * [SolrDocument::serialize](solrdocument.serialize) — Used for custom serialization * [SolrDocument::\_\_set](solrdocument.set) — Adds another field to the document * [SolrDocument::sort](solrdocument.sort) — Sorts the fields in the document * [SolrDocument::toArray](solrdocument.toarray) — Returns an array representation of the document * [SolrDocument::unserialize](solrdocument.unserialize) — Custom serialization of SolrDocument objects * [SolrDocument::\_\_unset](solrdocument.unset) — Removes a field from the document * [SolrDocument::valid](solrdocument.valid) — Checks if the current position internally is still valid php ldap_dn2ufn ldap\_dn2ufn ============ (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_dn2ufn — Convert DN to User Friendly Naming format ### Description ``` ldap_dn2ufn(string $dn): string|false ``` Turns the specified `dn`, into a more user-friendly form, stripping off type names. ### Parameters `dn` The distinguished name of an LDAP entity. ### Return Values Returns the user friendly name, or **`false`** on failure. php SQLite3::querySingle SQLite3::querySingle ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3::querySingle — Executes a query and returns a single result ### Description ``` public SQLite3::querySingle(string $query, bool $entireRow = false): mixed ``` Executes a query and returns a single result. ### Parameters `query` The SQL query to execute. `entireRow` By default, **querySingle()** returns the value of the first column returned by the query. If `entireRow` is **`true`**, then it returns an array of the entire first row. ### Return Values Returns the value of the first column of results or an array of the entire first row (if `entireRow` is **`true`**). If the query is valid but no results are returned, then **`null`** will be returned if `entireRow` is **`false`**, otherwise an empty array is returned. Invalid or failing queries will return **`false`**. ### Examples **Example #1 **SQLite3::querySingle()** example** ``` <?php $db = new SQLite3('mysqlitedb.db'); var_dump($db->querySingle('SELECT username FROM user WHERE userid=1')); print_r($db->querySingle('SELECT username, email FROM user WHERE userid=1', true)); ?> ``` The above example will output something similar to: ``` string(5) "Scott" Array ( [username] => Scott [email] => [email protected] ) ``` php ImagickDraw::setStrokeLineJoin ImagickDraw::setStrokeLineJoin ============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeLineJoin — Specifies the shape to be used at the corners of paths when they are stroked ### Description ``` public ImagickDraw::setStrokeLineJoin(int $linejoin): bool ``` **Warning**This function is currently not documented; only its argument list is available. Specifies the shape to be used at the corners of paths (or other vector shapes) when they are stroked. ### Parameters `linejoin` One of the [LINEJOIN](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.linejoin) constant (`imagick::LINEJOIN_*`). ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeLineJoin()** example** ``` <?php function setStrokeLineJoin($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeWidth(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(20);     $offset = 220;     $lineJoinStyle = [         \Imagick::LINEJOIN_MITER,         \Imagick::LINEJOIN_ROUND,         \Imagick::LINEJOIN_BEVEL,         ];     for ($x = 0; $x < count($lineJoinStyle); $x++) {         $draw->setStrokeLineJoin($lineJoinStyle[$x]);         $points = [             ['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],             ['x' => 20 * 5, 'y' => 20 * 5 + $x * $offset],             ['x' => 70 * 5, 'y' => 50 * 5 + $x * $offset],             ['x' => 40 * 5, 'y' => 10 * 5 + $x * $offset],         ];         $draw->polyline($points);     }     $image = new \Imagick();     $image->newImage(500, 700, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php SimpleXMLIterator::valid SimpleXMLIterator::valid ======================== (PHP 5, PHP 7, PHP 8) SimpleXMLIterator::valid — Check whether the current element is valid ### Description ``` public SimpleXMLIterator::valid(): bool ``` This method checks if the current element is valid after calls to [SimpleXMLIterator::rewind()](simplexmliterator.rewind) or [SimpleXMLIterator::next()](simplexmliterator.next). ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the current element is valid, otherwise **`false`** ### Examples **Example #1 Check whether the current element is valid** ``` <?php $xmlIterator = new SimpleXMLIterator('<books><book>SQL Basics</book></books>'); $xmlIterator->rewind(); // rewind to the first element echo var_dump($xmlIterator->valid()); // bool(true) $xmlIterator->next(); // advance to the next element echo var_dump($xmlIterator->valid()); // bool(false) because there is only one element ?> ``` php The DOMDocumentFragment class The DOMDocumentFragment class ============================= Class synopsis -------------- (PHP 5, PHP 7, PHP 8) class **DOMDocumentFragment** extends [DOMNode](class.domnode) implements [DOMParentNode](class.domparentnode) { /\* Properties \*/ public readonly ?[DOMElement](class.domelement) [$firstElementChild](class.domdocumentfragment#domdocumentfragment.props.firstelementchild); public readonly ?[DOMElement](class.domelement) [$lastElementChild](class.domdocumentfragment#domdocumentfragment.props.lastelementchild); public readonly int [$childElementCount](class.domdocumentfragment#domdocumentfragment.props.childelementcount); /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domdocumentfragment.construct)() ``` public appendXML(string $data): bool ``` /\* Inherited methods \*/ ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- childElementCount The number of child elements. firstElementChild First child element or **`null`**. lastElementChild Last child element or **`null`**. Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The firstElementChild, lastElementChild, and childElementCount properties have been added. | | 8.0.0 | **DOMDocumentFragment** implements [DOMParentNode](class.domparentnode) now. | Table of Contents ----------------- * [DOMDocumentFragment::appendXML](domdocumentfragment.appendxml) — Append raw XML data * [DOMDocumentFragment::\_\_construct](domdocumentfragment.construct) — Constructs a DOMDocumentFragment object
programming_docs
php key key === (PHP 4, PHP 5, PHP 7, PHP 8) key — Fetch a key from an array ### Description ``` key(array|object $array): int|string|null ``` **key()** returns the index element of the current array position. ### Parameters `array` The array. ### Return Values The **key()** function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, **key()** returns **`null`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function on objects is deprecated. Either use [get\_mangled\_object\_vars()](function.get-mangled-object-vars) on the object first, or use [ArrayIterator](class.arrayiterator). | ### Examples **Example #1 **key()** example** ``` <?php $array = array(     'fruit1' => 'apple',     'fruit2' => 'orange',     'fruit3' => 'grape',     'fruit4' => 'apple',     'fruit5' => 'apple'); // this cycle echoes all associative array // key where value equals "apple" while ($fruit_name = current($array)) {     if ($fruit_name == 'apple') {         echo key($array), "\n";     }     next($array); } ?> ``` The above example will output: ``` fruit1 fruit4 fruit5 ``` ### See Also * [current()](function.current) - Return the current element in an array * [next()](function.next) - Advance the internal pointer of an array * [array\_key\_first()](function.array-key-first) - Gets the first key of an array * [foreach](control-structures.foreach) php print print ===== (PHP 4, PHP 5, PHP 7, PHP 8) print — Output a string ### Description ``` print(string $expression): int ``` Outputs `expression`. `print` is not a function but a language construct. Its argument is the expression following the `print` keyword, and is not delimited by parentheses. The major differences to [echo](function.echo) are that `print` only accepts a single argument and always returns `1`. ### Parameters `expression` The expression to be output. Non-string values will be coerced to strings, even when [the `strict_types` directive](language.types.declarations#language.types.declarations.strict) is enabled. ### Return Values Returns `1`, always. ### Examples **Example #1 `print` examples** ``` <?php print "print does not require parentheses."; // No newline or space is added; the below outputs "helloworld" all on one line print "hello"; print "world"; print "This string spans multiple lines. The newlines will be output as well"; print "This string spans\nmultiple lines. The newlines will be\noutput as well."; // The argument can be any expression which produces a string $foo = "example"; print "foo is $foo"; // foo is example $fruits = ["lemon", "orange", "banana"]; print implode(" and ", $fruits); // lemon and orange and banana // Non-string expressions are coerced to string, even if declare(strict_types=1) is used print 6 * 7; // 42 // Because print has a return value, it can be used in expressions // The following outputs "hello world" if ( print "hello" ) {     echo " world"; } // The following outputs "true" ( 1 === 1 ) ? print 'true' : print 'false'; ?> ``` ### Notes > > **Note**: **Using with parentheses** > > > > Surrounding the argument to `print` with parentheses will not raise a syntax error, and produces syntax which looks like a normal function call. However, this can be misleading, because the parentheses are actually part of the expression being output, not part of the `print` syntax itself. > > > > ``` > <?php > print "hello"; > // outputs "hello" > > print("hello"); > // also outputs "hello", because ("hello") is a valid expression > > print(1 + 2) * 3; > // outputs "9"; the parentheses cause 1+2 to be evaluated first, then 3*3 > // the print statement sees the whole expression as one argument > > if ( print("hello") && false ) { >     print " - inside if"; > } > else { >     print " - inside else"; > } > // outputs " - inside if" > // the expression ("hello") && false is first evaluated, giving false > // this is coerced to the empty string "" and printed > // the print construct then returns 1, so code in the if block is run > ?> > ``` > When using `print` in a larger expression, placing both the keyword and its argument in parentheses may be necessary to give the intended result: > > > > ``` > <?php > if ( (print "hello") && false ) { >     print " - inside if"; > } > else { >     print " - inside else"; > } > // outputs "hello - inside else" > // unlike the previous example, the expression (print "hello") is evaluated first > // after outputting "hello", print returns 1 > // since 1 && false is false, code in the else block is run > > print "hello " && print "world"; > // outputs "world1"; print "world" is evaluated first, > // then the expression "hello " && 1 is passed to the left-hand print > > (print "hello ") && (print "world"); > // outputs "hello world"; the parentheses force the print expressions > // to be evaluated before the && > ?> > ``` > > **Note**: Because this is a language construct and not a function, it cannot be called using [variable functions](functions.variable-functions), or [named arguments](functions.arguments#functions.named-arguments). > > ### See Also * [echo](function.echo) - Output one or more strings * [printf()](function.printf) - Output a formatted string * [flush()](function.flush) - Flush system output buffer * [Ways to specify literal strings](language.types.string) php header header ====== (PHP 4, PHP 5, PHP 7, PHP 8) header — Send a raw HTTP header ### Description ``` header(string $header, bool $replace = true, int $response_code = 0): void ``` **header()** is used to send a raw HTTP header. See the [» HTTP/1.1 specification](http://www.faqs.org/rfcs/rfc2616) for more information on HTTP headers. Remember that **header()** must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. It is a very common error to read code with [include](function.include), or [require](function.require), functions, or another file access function, and have spaces or empty lines that are output before **header()** is called. The same problem exists when using a single PHP/HTML file. ``` <html> <?php /* This will give an error. Note the output  * above, which is before the header() call */ header('Location: http://www.example.com/'); exit; ?> ``` ### Parameters `header` The header string. There are two special-case header calls. The first is a header that starts with the string "`HTTP/`" (case is not significant), which will be used to figure out the HTTP status code to send. For example, if you have configured Apache to use a PHP script to handle requests for missing files (using the `ErrorDocument` directive), you may want to make sure that your script generates the proper status code. ``` <?php // This example illustrates the "HTTP/" special case // Better alternatives in typical use cases include: // 1. header($_SERVER["SERVER_PROTOCOL"] . " 404 Not Found"); //    (to override http status messages for clients that are still using HTTP/1.0) // 2. http_response_code(404); (to use the default message) header("HTTP/1.1 404 Not Found"); ?> ``` The second special case is the "Location:" header. Not only does it send this header back to the browser, but it also returns a `REDIRECT` (302) status code to the browser unless the `201` or a `3xx` status code has already been set. ``` <?php header("Location: http://www.example.com/"); /* Redirect browser */ /* Make sure that code below does not get executed when we redirect. */ exit; ?> ``` `replace` The optional `replace` parameter indicates whether the header should replace a previous similar header, or add a second header of the same type. By default it will replace, but if you pass in **`false`** as the second argument you can force multiple headers of the same type. For example: ``` <?php header('WWW-Authenticate: Negotiate'); header('WWW-Authenticate: NTLM', false); ?> ``` `response_code` Forces the HTTP response code to the specified value. Note that this parameter only has an effect if the `header` is not empty. ### Return Values No value is returned. ### Errors/Exceptions On failure to schedule the header to be sent, **header()** issues an **`E_WARNING`** level error. ### Examples **Example #1 Download dialog** If you want the user to be prompted to save the data you are sending, such as a generated PDF file, you can use the [» Content-Disposition](http://www.faqs.org/rfcs/rfc2183) header to supply a recommended filename and force the browser to display the save dialog. ``` <?php // We'll be outputting a PDF header('Content-Type: application/pdf'); // It will be called downloaded.pdf header('Content-Disposition: attachment; filename="downloaded.pdf"'); // The PDF source is in original.pdf readfile('original.pdf'); ?> ``` **Example #2 Caching directives** PHP scripts often generate dynamic content that must not be cached by the client browser or any proxy caches between the server and the client browser. Many proxies and clients can be forced to disable caching with: ``` <?php header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past ?> ``` > > **Note**: > > > You may find that your pages aren't cached even if you don't output all of the headers above. There are a number of options that users may be able to set for their browser that change its default caching behavior. By sending the headers above, you should override any settings that may otherwise cause the output of your script to be cached. > > Additionally, [session\_cache\_limiter()](function.session-cache-limiter) and the `session.cache_limiter` configuration setting can be used to automatically generate the correct caching-related headers when sessions are being used. > > ### Notes > > **Note**: > > > Headers will only be accessible and output when a SAPI that supports them is in use. > > > > **Note**: > > > You can use output buffering to get around this problem, with the overhead of all of your output to the browser being buffered in the server until you send it. You can do this by calling [ob\_start()](function.ob-start) and [ob\_end\_flush()](function.ob-end-flush) in your script, or setting the `output_buffering` configuration directive on in your php.ini or server configuration files. > > > > **Note**: > > > The HTTP status header line will always be the first sent to the client, regardless of the actual **header()** call being the first or not. The status may be overridden by calling **header()** with a new status line at any time unless the HTTP headers have already been sent. > > > > **Note**: > > > Most contemporary clients accept relative URIs as argument to [» Location:](http://tools.ietf.org/html/rfc7231#section-7.1.2), but some older clients require an absolute URI including the scheme, hostname and absolute path. You can usually use [$\_SERVER['HTTP\_HOST']](reserved.variables.server), [$\_SERVER['PHP\_SELF']](reserved.variables.server) and [dirname()](function.dirname) to make an absolute URI from a relative one yourself: > > > > ``` > <?php > /* Redirect to a different page in the current directory that was requested */ > $host  = $_SERVER['HTTP_HOST']; > $uri   = rtrim(dirname($_SERVER['PHP_SELF']), '/\\'); > $extra = 'mypage.php'; > header("Location: http://$host$uri/$extra"); > exit; > ?> > ``` > > > **Note**: > > > Session ID is not passed with Location header even if [session.use\_trans\_sid](https://www.php.net/manual/en/session.configuration.php#ini.session.use-trans-sid) is enabled. It must by passed manually using **`SID`** constant. > > ### See Also * [headers\_sent()](function.headers-sent) - Checks if or where headers have been sent * [setcookie()](function.setcookie) - Send a cookie * [http\_response\_code()](function.http-response-code) - Get or Set the HTTP response code * [header\_remove()](function.header-remove) - Remove previously set headers * **header\_list()** * The section on [HTTP authentication](https://www.php.net/manual/en/features.http-auth.php) php ReflectionClass::getEndLine ReflectionClass::getEndLine =========================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getEndLine — Gets end line ### Description ``` public ReflectionClass::getEndLine(): int|false ``` Gets end line number from a user-defined class definition. ### Parameters This function has no parameters. ### Return Values The ending line number of the user defined class, or **`false`** if unknown. ### Examples **Example #1 **ReflectionClass::getEndLine()** example** ``` <?php // Test Class class TestClass { } $rc = new ReflectionClass('TestClass'); echo $rc->getEndLine(); ?> ``` The above example will output: ``` 3 ``` ### See Also * [ReflectionClass::getStartLine()](reflectionclass.getstartline) - Gets starting line number php None Subpatterns ----------- Subpatterns are delimited by parentheses (round brackets), which can be nested. Marking part of a pattern as a subpattern does two things: 1. It localizes a set of alternatives. For example, the pattern `cat(aract|erpillar|)` matches one of the words "cat", "cataract", or "caterpillar". Without the parentheses, it would match "cataract", "erpillar" or the empty string. 2. It sets up the subpattern as a capturing subpattern (as defined above). When the whole pattern matches, that portion of the subject string that matched the subpattern is passed back to the caller via the *ovector* argument of **pcre\_exec()**. Opening parentheses are counted from left to right (starting from 1) to obtain the numbers of the capturing subpatterns. For example, if the string "the red king" is matched against the pattern `the ((red|white) (king|queen))` the captured substrings are "red king", "red", and "king", and are numbered 1, 2, and 3. The fact that plain parentheses fulfill two functions is not always helpful. There are often times when a grouping subpattern is required without a capturing requirement. If an opening parenthesis is followed by "?:", the subpattern does not do any capturing, and is not counted when computing the number of any subsequent capturing subpatterns. For example, if the string "the white queen" is matched against the pattern `the ((?:red|white) (king|queen))` the captured substrings are "white queen" and "queen", and are numbered 1 and 2. The maximum number of captured substrings is 65535. It may not be possible to compile such large patterns, however, depending on the configuration options of libpcre. As a convenient shorthand, if any option settings are required at the start of a non-capturing subpattern, the option letters may appear between the "?" and the ":". Thus the two patterns ``` (?i:saturday|sunday) (?:(?i)saturday|sunday) ``` match exactly the same set of strings. Because alternative branches are tried from left to right, and options are not reset until the end of the subpattern is reached, an option setting in one branch does affect subsequent branches, so the above patterns match "SUNDAY" as well as "Saturday". It is possible to name a subpattern using the syntax `(?P<name>pattern)`. This subpattern will then be indexed in the matches array by its normal numeric position and also by name. There are two alternative syntaxes `(?<name>pattern)` and `(?'name'pattern)`. Sometimes it is necessary to have multiple matching, but alternating subgroups in a regular expression. Normally, each of these would be given their own backreference number even though only one of them would ever possibly match. To overcome this, the `(?|` syntax allows having duplicate numbers. Consider the following regex matched against the string `Sunday`: ``` (?:(Sat)ur|(Sun))day ``` Here `Sun` is stored in backreference 2, while backreference 1 is empty. Matching yields `Sat` in backreference 1 while backreference 2 does not exist. Changing the pattern to use the `(?|` fixes this problem: ``` (?|(Sat)ur|(Sun))day ``` Using this pattern, both `Sun` and `Sat` would be stored in backreference 1. php Gmagick::setimagewhitepoint Gmagick::setimagewhitepoint =========================== (PECL gmagick >= Unknown) Gmagick::setimagewhitepoint — Sets the image chromaticity white point ### Description ``` public Gmagick::setimagewhitepoint(float $x, float $y): Gmagick ``` Sets the image chromaticity white point. ### Parameters `x` The white x-point. `y` The white y-point. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php ReflectionObject::__construct ReflectionObject::\_\_construct =============================== (PHP 5, PHP 7, PHP 8) ReflectionObject::\_\_construct — Constructs a ReflectionObject ### Description public **ReflectionObject::\_\_construct**(object `$object`) Constructs a [ReflectionObject](class.reflectionobject). ### Parameters `object` An object instance. ### See Also * [ReflectionObject::export()](reflectionobject.export) - Export * [Constructors](language.oop5.decon#language.oop5.decon.constructor) php Countable::count Countable::count ================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Countable::count — Count elements of an object ### Description ``` public Countable::count(): int ``` This method is executed when using the [count()](function.count) function on an object implementing [Countable](class.countable). ### Parameters This function has no parameters. ### Return Values The custom count as an int. > > **Note**: > > > The return value is cast to an int. > > ### Examples **Example #1 **Countable::count()** example** ``` <?php class myCounter implements Countable {     private $count = 0;     public function count() {         return ++$this->count;     } } $counter = new myCounter; for($i=0; $i<10; ++$i) {     echo "I have been count()ed " . count($counter) . " times\n"; } ?> ``` The above example will output something similar to: ``` I have been count()ed 1 times I have been count()ed 2 times I have been count()ed 3 times I have been count()ed 4 times I have been count()ed 5 times I have been count()ed 6 times I have been count()ed 7 times I have been count()ed 8 times I have been count()ed 9 times I have been count()ed 10 times ``` php EventBufferEvent::sslGetCipherName EventBufferEvent::sslGetCipherName ================================== (PECL event >= 1.10.0) EventBufferEvent::sslGetCipherName — Returns the current cipher name of the SSL connection ### Description ``` public EventBufferEvent::sslGetCipherName(): string ``` Retrieves name of cipher used by current SSL connection. > > **Note**: > > > This function is available only if `Event` is compiled with OpenSSL support. > > ### Parameters This function has no parameters. ### Return Values Returns the current cipher name of the SSL connection, or **`false`** on error. php DOMElement::getAttributeNode DOMElement::getAttributeNode ============================ (PHP 5, PHP 7, PHP 8) DOMElement::getAttributeNode — Returns attribute node ### Description ``` public DOMElement::getAttributeNode(string $qualifiedName): DOMAttr|DOMNameSpaceNode|false ``` Returns the attribute node with name `qualifiedName` for the current element. ### Parameters `qualifiedName` The name of the attribute. ### Return Values The attribute node. Note that for XML namespace declarations (`xmlns` and `xmlns:*` attributes) an instance of **DOMNameSpaceNode** is returned instead of a [DOMAttr](class.domattr). ### See Also * [DOMElement::hasAttribute()](domelement.hasattribute) - Checks to see if attribute exists * [DOMElement::setAttributeNode()](domelement.setattributenode) - Adds new attribute node to element * [DOMElement::removeAttributeNode()](domelement.removeattributenode) - Removes attribute
programming_docs
php gethostbyname gethostbyname ============= (PHP 4, PHP 5, PHP 7, PHP 8) gethostbyname — Get the IPv4 address corresponding to a given Internet host name ### Description ``` gethostbyname(string $hostname): string ``` Returns the IPv4 address of the Internet host specified by `hostname`. ### Parameters `hostname` The host name. ### Return Values Returns the IPv4 address or a string containing the unmodified `hostname` on failure. ### Examples **Example #1 A simple **gethostbyname()** example** ``` <?php $ip = gethostbyname('www.example.com'); echo $ip; ?> ``` ### See Also * [gethostbyaddr()](function.gethostbyaddr) - Get the Internet host name corresponding to a given IP address * [gethostbynamel()](function.gethostbynamel) - Get a list of IPv4 addresses corresponding to a given Internet host name * [inet\_pton()](function.inet-pton) - Converts a human readable IP address to its packed in\_addr representation * [inet\_ntop()](function.inet-ntop) - Converts a packed internet address to a human readable representation php Gmagick::resizeimage Gmagick::resizeimage ==================== (PECL gmagick >= Unknown) Gmagick::resizeimage — Scales an image ### Description ``` public Gmagick::resizeimage( int $width, int $height, int $filter, float $blur, bool $fit = false ): Gmagick ``` Scales an image to the desired dimensions with a filter. ### Parameters `width` The number of columns in the scaled image. `height` The number of rows in the scaled image. `filter` Image filter to use. `blur` The blur factor where larger than 1 is blurry, lesser than 1 is sharp. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Gmagick::getimageresolution Gmagick::getimageresolution =========================== (PECL gmagick >= Unknown) Gmagick::getimageresolution — Gets the image X and Y resolution ### Description ``` public Gmagick::getimageresolution(): array ``` Returns the resolution as an array. ### Parameters This function has no parameters. ### Return Values Returns the resolution as an array. ### Errors/Exceptions Throws an **GmagickException** on error. php Event::del Event::del ========== (PECL event >= 1.2.6-beta) Event::del — Makes event non-pending ### Description ``` public Event::del(): bool ``` Removes an event from the set of monitored events, i.e. makes it non-pending. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [Event::add()](event.add) - Makes event pending php Imagick::resetImagePage Imagick::resetImagePage ======================= (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::resetImagePage — Reset image page ### Description ``` public Imagick::resetImagePage(string $page): bool ``` The page definition as a string. The string is in format WxH+x+y. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer. ### Parameters `page` The page definition. For example `7168x5147+0+0` ### Return Values Returns **`true`** on success. php ArrayIterator::rewind ArrayIterator::rewind ===================== (PHP 5, PHP 7, PHP 8) ArrayIterator::rewind — Rewind array back to the start ### Description ``` public ArrayIterator::rewind(): void ``` This rewinds the iterator to the beginning. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **ArrayIterator::rewind()** example** ``` <?php $arrayobject = new ArrayObject(); $arrayobject[] = 'zero'; $arrayobject[] = 'one'; $arrayobject[] = 'two'; $iterator = $arrayobject->getIterator(); $iterator->next(); echo $iterator->key(); //1 $iterator->rewind(); //rewinding to the beginning echo $iterator->key(); //0 ?> ``` php RarArchive::isBroken RarArchive::isBroken ==================== rar\_broken\_is =============== (PECL rar >= 3.0.0) RarArchive::isBroken -- rar\_broken\_is — Test whether an archive is broken (incomplete) ### Description Object-oriented style (method): ``` public RarArchive::isBroken(): bool ``` Procedural style: ``` rar_broken_is(RarArchive $rarfile): bool ``` This function determines whether an archive is incomplete, i.e., if a volume is missing or a volume is truncated. ### Parameters `rarfile` A [RarArchive](class.rararchive) object, opened with [rar\_open()](rararchive.open). ### Return Values Returns **`true`** if the archive is broken, **`false`** otherwise. This function may also return **`false`** if the passed file has already been closed. The only way to tell the two cases apart is to enable exceptions with [RarException::setUsingExceptions()](rarexception.setusingexceptions); however, this should be unnecessary as a program should not operate on closed files. ### Examples **Example #1 Object-oriented style** ``` <?php function retnull() { return null; } $file = dirname(__FILE__) . "/multi_broken.part1.rar"; /* Third argument is used to omit notice */ $arch = RarArchive::open($file, null, 'retnull'); var_dump($arch->isBroken()); ?> ``` The above example will output something similar to: ``` bool(true) ``` **Example #2 Procedural style** ``` <?php function retnull() { return null; } $file = dirname(__FILE__) . "/multi_broken.part1.rar"; /* Third argument is used to omit notice */ $arch = rar_open($file, null, 'retnull'); var_dump(rar_broken_is($arch)); ?> ``` ### See Also * [RarArchive::setAllowBroken()](rararchive.setallowbroken) - Whether opening broken archives is allowed php DateInterval::__construct DateInterval::\_\_construct =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) DateInterval::\_\_construct — Creates a new DateInterval object ### Description public **DateInterval::\_\_construct**(string `$duration`) Creates a new DateInterval object. ### Parameters `duration` An interval specification. The format starts with the letter `P`, for period. Each duration period is represented by an integer value followed by a period designator. If the duration contains time elements, that portion of the specification is preceded by the letter `T`. **`duration` Period Designators** | Period Designator | Description | | --- | --- | | `Y` | years | | `M` | months | | `D` | days | | `W` | weeks. Converted into days. Prior to PHP 8.0.0, can not be combined with `D`. | | `H` | hours | | `M` | minutes | | `S` | seconds | Here are some simple examples. Two days is `P2D`. Two seconds is `PT2S`. Six years and five minutes is `P6YT5M`. > > **Note**: > > > The unit types must be entered from the largest scale unit on the left to the smallest scale unit on the right. So years before months, months before days, days before minutes, etc. Thus one year and four days must be represented as `P1Y4D`, not `P4D1Y`. > > The specification can also be represented as a date time. A sample of one year and four days would be `P0001-00-04T00:00:00`. But the values in this format can not exceed a given period's roll-over-point (e.g. `25` hours is invalid). These formats are based on the [» ISO 8601 duration specification](http://en.wikipedia.org/wiki/Iso8601#Durations). ### Errors/Exceptions Throws an [Exception](class.exception) when the `duration` cannot be parsed as an interval. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | Only the `y` to `f`, `invert`, and `days` will be visible, including a new `from_string` boolean property. | | 8.0.0 | `W` can be combined with `D`. | ### Examples **Example #1 Constructing and using [DateInterval](class.dateinterval) objects** ``` <?php // Create a specific date $someDate = \DateTime::createFromFormat("Y-m-d H:i", "2022-08-25 14:18"); // Create interval $interval = new \DateInterval("P7D"); // Add interval $someDate->add($interval); // Convert interval to string echo $interval->format("%d"); ``` The above example will output: 7 **Example #2 [DateInterval](class.dateinterval) example** ``` <?php $interval = new DateInterval('P1W2D'); var_dump($interval); ?> ``` Output of the above example in PHP 8.2: ``` object(DateInterval)#1 (10) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(9) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["invert"]=> int(0) ["days"]=> bool(false) ["from_string"]=> bool(false) } ``` Output of the above example in PHP 8: ``` object(DateInterval)#1 (16) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(9) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> bool(false) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) } ``` Output of the above example in PHP 7: ``` object(DateInterval)#1 (16) { ["y"]=> int(0) ["m"]=> int(0) ["d"]=> int(2) ["h"]=> int(0) ["i"]=> int(0) ["s"]=> int(0) ["f"]=> float(0) ["weekday"]=> int(0) ["weekday_behavior"]=> int(0) ["first_last_day_of"]=> int(0) ["invert"]=> int(0) ["days"]=> bool(false) ["special_type"]=> int(0) ["special_amount"]=> int(0) ["have_weekday_relative"]=> int(0) ["have_special_relative"]=> int(0) } ``` ### See Also * [DateInterval::format()](dateinterval.format) - Formats the interval * [DateTime::add()](datetime.add) - Modifies a DateTime object, with added amount of days, months, years, hours, minutes and seconds * [DateTime::sub()](datetime.sub) - Subtracts an amount of days, months, years, hours, minutes and seconds from a DateTime object * [DateTime::diff()](datetime.diff) - Returns the difference between two DateTime objects php fbird_param_info fbird\_param\_info ================== (PHP 5, PHP 7 < 7.4.0) fbird\_param\_info — Alias of [ibase\_param\_info()](function.ibase-param-info) ### Description This function is an alias of: [ibase\_param\_info()](function.ibase-param-info). ### See Also * [fbird\_field\_info()](function.fbird-field-info) - Alias of ibase\_field\_info * [fbird\_num\_params()](function.fbird-num-params) - Alias of ibase\_num\_params php Componere\Patch::isApplied Componere\Patch::isApplied ========================== (Componere 2 >= 2.1.0) Componere\Patch::isApplied — State Detection ### Description ``` public Componere\Patch::isApplied(): bool ``` php ftp_size ftp\_size ========= (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_size — Returns the size of the given file ### Description ``` ftp_size(FTP\Connection $ftp, string $filename): int ``` **ftp\_size()** returns the size of the given file in bytes. > > **Note**: > > > Not all servers support this feature. > > ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `filename` The remote file. ### Return Values Returns the file size on success, or -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_size()** example** ``` <?php $file = 'somefile.txt'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // get the size of $file $res = ftp_size($ftp, $file); if ($res != -1) {     echo "size of $file is $res bytes"; } else {     echo "couldn't get the size"; } // close the connection ftp_close($ftp); ?> ``` ### See Also * [ftp\_rawlist()](function.ftp-rawlist) - Returns a detailed list of files in the given directory php mysqli_stmt::more_results mysqli\_stmt::more\_results =========================== mysqli\_stmt\_more\_results =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli\_stmt::more\_results -- mysqli\_stmt\_more\_results — Check if there are more query results from a multiple query ### Description Object-oriented style ``` public mysqli_stmt::more_results(): bool ``` Procedural style: ``` mysqli_stmt_more_results(mysqli_stmt $statement): bool ``` Checks if there are more query results from a multiple query. > > **Note**: > > > Available only with [mysqlnd](https://www.php.net/manual/en/book.mysqlnd.php). > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values Returns **`true`** if more results exist, otherwise **`false`**. ### See Also * [mysqli\_stmt::next\_result()](mysqli-stmt.next-result) - Reads the next result from a multiple query * [mysqli::multi\_query()](mysqli.multi-query) - Performs one or more queries on the database php mb_encode_numericentity mb\_encode\_numericentity ========================= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_encode\_numericentity — Encode character to HTML numeric string reference ### Description ``` mb_encode_numericentity( string $string, array $map, ?string $encoding = null, bool $hex = false ): string ``` Converts specified character codes in string `string` from character code to HTML numeric character reference. ### Parameters `string` The string being encoded. `map` `map` is array specifies code area to convert. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. `hex` Whether the returned entity reference should be in hexadecimal notation (otherwise it is in decimal notation). ### Return Values The converted string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### Examples **Example #1 `map` example** ``` <?php $convmap = array (  int start_code1, int end_code1, int offset1, int mask1,  int start_code2, int end_code2, int offset2, int mask2,  ........  int start_codeN, int end_codeN, int offsetN, int maskN ); // Specify Unicode value for start_codeN and end_codeN // Add offsetN to value and take bit-wise 'AND' with maskN, then // it converts value to numeric string reference. ?> ``` **Example #2 **mb\_encode\_numericentity()** example** ``` <?php /* Convert Left side of ISO-8859-1 to HTML numeric character reference */ $convmap = array(0x80, 0xff, 0, 0xff); $str = mb_encode_numericentity($str, $convmap, "ISO-8859-1"); /* Convert user defined SJIS-win code in block 95-104 to numeric    string reference */ $convmap = array(        0xe000, 0xe03e, 0x1040, 0xffff,        0xe03f, 0xe0bb, 0x1041, 0xffff,        0xe0bc, 0xe0fa, 0x1084, 0xffff,        0xe0fb, 0xe177, 0x1085, 0xffff,        0xe178, 0xe1b6, 0x10c8, 0xffff,        0xe1b7, 0xe233, 0x10c9, 0xffff,        0xe234, 0xe272, 0x110c, 0xffff,        0xe273, 0xe2ef, 0x110d, 0xffff,        0xe2f0, 0xe32e, 0x1150, 0xffff,        0xe32f, 0xe3ab, 0x1151, 0xffff ); $str = mb_encode_numericentity($str, $convmap, "sjis-win"); ?> ``` ### See Also * [mb\_decode\_numericentity()](function.mb-decode-numericentity) - Decode HTML numeric string reference to character php SolrObject::getPropertyNames SolrObject::getPropertyNames ============================ (PECL solr >= 0.9.2) SolrObject::getPropertyNames — Returns an array of all the names of the properties ### Description ``` public SolrObject::getPropertyNames(): array ``` Returns an array of all the names of the properties ### Parameters This function has no parameters. ### Return Values Returns an array. php curl_upkeep curl\_upkeep ============ (PHP 8 >= 8.2.0) curl\_upkeep — Performs any connection upkeep checks ### Description ``` curl_upkeep(CurlHandle $handle): bool ``` Available if built against libcurl >= 7.62.0. Some protocols have "connection upkeep" mechanisms. These mechanisms usually send some traffic on existing connections in order to keep them alive; this can prevent connections from being closed due to overzealous firewalls, for example. Connection upkeep is currently available only for HTTP/2 connections. A small amount of traffic is usually sent to keep a connection alive. HTTP/2 maintains its connection by sending a HTTP/2 PING frame. ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **curl\_upkeep()** example** ``` <?php $url = "https://example.com"; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_2_0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_UPKEEP_INTERVAL_MS, 200); if (curl_exec($ch)) {     usleep(300);     var_dump(curl_upkeep($ch)); } curl_close($ch); ?> ``` ### See Also * [curl\_init()](function.curl-init) - Initialize a cURL session php IntlIterator::next IntlIterator::next ================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlIterator::next — Move forward to the next element ### Description ``` public IntlIterator::next(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php stats_dens_pmf_poisson stats\_dens\_pmf\_poisson ========================= (PECL stats >= 1.0.0) stats\_dens\_pmf\_poisson — Probability mass function of the Poisson distribution ### Description ``` stats_dens_pmf_poisson(float $x, float $lb): float ``` Returns the probability mass at `x`, where the random variable follows the Poisson distribution whose parameter is `lb`. ### Parameters `x` The value at which the probability mass is calculated `lb` The parameter of the Poisson distribution ### Return Values The probability mass at `x` or **`false`** for failure. php snmp_read_mib snmp\_read\_mib =============== (PHP 5, PHP 7, PHP 8) snmp\_read\_mib — Reads and parses a MIB file into the active MIB tree ### Description ``` snmp_read_mib(string $filename): bool ``` This function is used to load additional, e.g. vendor specific, MIBs so that human readable OIDs like `VENDOR-MIB::foo.1` instead of error prone numeric OIDs can be used. The order in which the MIBs are loaded does matter as the underlying Net-SNMP library will print warnings if referenced objects cannot be resolved. ### Parameters `filename` The filename of the MIB. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Using **snmp\_read\_mib()**** ``` <?php  print_r( snmprealwalk('localhost', 'public', '.1.3.6.1.2.1.2.3.4.5') );    snmp_read_mib('./FOO-BAR-MIB.txt');  print_r( snmprealwalk('localhost', 'public', 'FOO-BAR-MIB::someTable') ); ?> ``` The above example is made up but the results would look like: ``` Array ( [iso.3.6.1.2.1.2.3.4.5.0] => Gauge32: 6 ) Array ( [FOO-BAR-MIB::someTable.0] => Gauge32: 6 ) ``` php GearmanWorker::returnCode GearmanWorker::returnCode ========================= (PECL gearman >= 0.5.0) GearmanWorker::returnCode — Get last Gearman return code ### Description ``` public GearmanWorker::returnCode(): int ``` Returns the last Gearman return code. ### Parameters This function has no parameters. ### Return Values A valid Gearman return code. ### See Also * [GearmanWorker::error()](gearmanworker.error) - Get the last error encountered * [GearmanWorker::getErrno()](gearmanworker.geterrno) - Get errno
programming_docs
php DOMElement::setIdAttributeNode DOMElement::setIdAttributeNode ============================== (PHP 5, PHP 7, PHP 8) DOMElement::setIdAttributeNode — Declares the attribute specified by node to be of type ID ### Description ``` public DOMElement::setIdAttributeNode(DOMAttr $attr, bool $isId): void ``` Declares the attribute specified by `attr` to be of type ID. ### Parameters `attr` The attribute node. `isId` Set it to **`true`** if you want `name` to be of type ID, **`false`** otherwise. ### Return Values No value is returned. ### Errors/Exceptions **`DOM_NO_MODIFICATION_ALLOWED_ERR`** Raised if the node is readonly. **`DOM_NOT_FOUND`** Raised if `name` is not an attribute of this element. ### See Also * [DOMDocument::getElementById()](domdocument.getelementbyid) - Searches for an element with a certain id * [DOMElement::setIdAttribute()](domelement.setidattribute) - Declares the attribute specified by name to be of type ID * [DOMElement::setIdAttributeNS()](domelement.setidattributens) - Declares the attribute specified by local name and namespace URI to be of type ID php Imagick::averageImages Imagick::averageImages ====================== (PECL imagick 2, PECL imagick 3) Imagick::averageImages — Average a set of images **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::averageImages(): Imagick ``` Average a set of images. ### Parameters This function has no parameters. ### Return Values Returns a new Imagick object on success. ### Errors/Exceptions Throws ImagickException on error. php ImagickDraw::pathStart ImagickDraw::pathStart ====================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pathStart — Declares the start of a path drawing list ### Description ``` public ImagickDraw::pathStart(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Declares the start of a path drawing list which is terminated by a matching DrawPathFinish() command. All other DrawPath commands must be enclosed between a and a DrawPathFinish() command. This is because path drawing commands are subordinate commands and they do not function by themselves. ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::pathStart()** example** ``` <?php function pathStart($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeOpacity(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $draw->setFontSize(72);     $draw->pathStart();     $draw->pathMoveToAbsolute(50, 50);     $draw->pathLineToAbsolute(100, 50);     $draw->pathLineToRelative(0, 50);     $draw->pathLineToHorizontalRelative(-50);     $draw->pathFinish();     $draw->pathStart();     $draw->pathMoveToAbsolute(50, 50);     $draw->pathMoveToRelative(300, 0);     $draw->pathLineToRelative(50, 0);     $draw->pathLineToVerticalRelative(50);     $draw->pathLineToHorizontalAbsolute(350);     $draw->pathclose();     $draw->pathFinish();     $draw->pathStart();     $draw->pathMoveToAbsolute(50, 300);     $draw->pathCurveToAbsolute(50, 300, 100, 200, 300, 300);     $draw->pathLineToVerticalAbsolute(350);     $draw->pathFinish();     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php VarnishStat::__construct VarnishStat::\_\_construct ========================== (PECL varnish >= 0.3) VarnishStat::\_\_construct — VarnishStat constructor ### Description ``` public VarnishStat::__construct(array $args = ?) ``` ### Parameters `args` Configuration arguments. The possible keys are: ``` VARNISH_CONFIG_IDENT - local varnish instance ident path ``` ### Return Values php ReflectionGenerator::getTrace ReflectionGenerator::getTrace ============================= (PHP 7, PHP 8) ReflectionGenerator::getTrace — Gets the trace of the executing generator ### Description ``` public ReflectionGenerator::getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array ``` Get the trace of the currently executing generator. ### Parameters `options` The value of `options` can be any of the following flags. **Available options**| Option | Description | | --- | --- | | **`DEBUG_BACKTRACE_PROVIDE_OBJECT`** | Default. | | **`DEBUG_BACKTRACE_IGNORE_ARGS`** | Don't include the argument information for functions in the stack trace. | ### Return Values Returns the trace of the currently executing generator. ### Examples **Example #1 **ReflectionGenerator::getTrace()** example** ``` <?php function foo() {     yield 1; } function bar() {     yield from foo(); } function baz() {     yield from bar(); } $gen = baz(); $gen->valid(); // start the generator var_dump((new ReflectionGenerator($gen))->getTrace()); ``` The above example will output something similar to: ``` array(2) { [0]=> array(4) { ["file"]=> string(18) "example.php" ["line"]=> int(8) ["function"]=> string(3) "foo" ["args"]=> array(0) { } } [1]=> array(4) { ["file"]=> string(18) "example.php" ["line"]=> int(12) ["function"]=> string(3) "bar" ["args"]=> array(0) { } } } ``` ### See Also * [ReflectionGenerator::getFunction()](reflectiongenerator.getfunction) - Gets the function name of the generator * [ReflectionGenerator::getThis()](reflectiongenerator.getthis) - Gets the $this value of the generator php ImagickDraw::setStrokeAlpha ImagickDraw::setStrokeAlpha =========================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeAlpha — Specifies the opacity of stroked object outlines ### Description ``` public ImagickDraw::setStrokeAlpha(float $opacity): bool ``` **Warning**This function is currently not documented; only its argument list is available. Specifies the opacity of stroked object outlines. ### Parameters `opacity` opacity ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeAlpha()** example** ``` <?php function setStrokeAlpha($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(4);     $draw->line(100, 100, 400, 145);     $draw->rectangle(100, 200, 225, 350);     $draw->setStrokeOpacity(0.1);     $draw->line(100, 120, 400, 165);     $draw->rectangle(275, 200, 400, 350);     $image = new \Imagick();     $image->newImage(500, 400, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php Memcached::getServerByKey Memcached::getServerByKey ========================= (PECL memcached >= 0.1.0) Memcached::getServerByKey — Map a key to a server ### Description ``` public Memcached::getServerByKey(string $server_key): array ``` **Memcached::getServerByKey()** returns the server that would be selected by a particular `server_key` in all the **Memcached::\*ByKey()** operations. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. ### Return Values Returns an array containing three keys of `host`, `port`, and `weight` on success or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary. ### Examples **Example #1 **Memcached::getServerByKey()** example** ``` <?php $m = new Memcached(); $m->addServers(array(     array('mem1.domain.com', 11211, 40),     array('mem2.domain.com', 11211, 40),     array('mem3.domain.com', 11211, 20), )); $m->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true); var_dump($m->getServerByKey('user')); var_dump($m->getServerByKey('log')); var_dump($m->getServerByKey('ip')); ?> ``` The above example will output something similar to: ``` array(3) { ["host"]=> string(15) "mem3.domain.com" ["port"]=> int(11211) ["weight"]=> int(20) } array(3) { ["host"]=> string(15) "mem2.domain.com" ["port"]=> int(11211) ["weight"]=> int(40) } array(3) { ["host"]=> string(15) "mem2.domain.com" ["port"]=> int(11211) ["weight"]=> int(40) } ``` php svn_fs_revision_root svn\_fs\_revision\_root ======================= (PECL svn >= 0.1.0) svn\_fs\_revision\_root — Get a handle on a specific version of the repository root ### Description ``` svn_fs_revision_root(resource $fs, int $revnum): resource ``` **Warning**This function is currently not documented; only its argument list is available. Get a handle on a specific version of the repository root ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php SolrResponse::getRawResponse SolrResponse::getRawResponse ============================ (PECL solr >= 0.9.2) SolrResponse::getRawResponse — Returns the raw response from the server ### Description ``` public SolrResponse::getRawResponse(): string ``` Returns the raw response from the server. ### Parameters This function has no parameters. ### Return Values Returns the raw response from the server. php SQLite3::createCollation SQLite3::createCollation ======================== (PHP 5 >= 5.3.11, PHP 7, PHP 8) SQLite3::createCollation — Registers a PHP function for use as an SQL collating function ### Description ``` public SQLite3::createCollation(string $name, callable $callback): bool ``` Registers a PHP function or user-defined function for use as a collating function within SQL statements. ### Parameters `name` Name of the SQL collating function to be created or redefined `callback` The name of a PHP function or user-defined function to apply as a callback, defining the behavior of the collation. It should accept two values and return as [strcmp()](function.strcmp) does, i.e. it should return -1, 1, or 0 if the first string sorts before, sorts after, or is equal to the second. This function need to be defined as: ``` collation(mixed $value1, mixed $value2): int ``` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SQLite3::createCollation()** example** Register the PHP function [strnatcmp()](function.strnatcmp) as a collating sequence in the SQLite3 database. ``` <?php $db = new SQLite3(":memory:"); $db->exec("CREATE TABLE test (col1 string)"); $db->exec("INSERT INTO test VALUES ('a1')"); $db->exec("INSERT INTO test VALUES ('a10')"); $db->exec("INSERT INTO test VALUES ('a2')"); $db->createCollation('NATURAL_CMP', 'strnatcmp'); $defaultSort = $db->query("SELECT col1 FROM test ORDER BY col1"); $naturalSort = $db->query("SELECT col1 FROM test ORDER BY col1 COLLATE NATURAL_CMP"); echo "default:\n"; while ($row = $defaultSort->fetchArray()){     echo $row['col1'], "\n"; } echo "\nnatural:\n"; while ($row = $naturalSort->fetchArray()){     echo $row['col1'], "\n"; } $db->close(); ?> ``` The above example will output: ``` default: a1 a10 a2 natural: a1 a2 a10 ``` ### See Also * The SQLite collation documentation: [» http://sqlite.org/datatype3.html#collation](http://sqlite.org/datatype3.html#collation) php Phar::decompressFiles Phar::decompressFiles ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::decompressFiles — Decompresses all files in the current Phar archive ### Description ``` public Phar::decompressFiles(): bool ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > For tar-based phar archives, this method throws a [BadMethodCallException](class.badmethodcallexception), as compression of individual files within a tar archive is not supported by the file format. Use [Phar::compress()](phar.compress) to compress an entire tar-based phar archive. For Zip-based and phar-based phar archives, this method decompresses all files in the Phar archive. The [zlib](https://www.php.net/manual/en/ref.zlib.php) or [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extensions must be enabled to take advantage of this feature if any files are compressed using bzip2/zlib compression. As with all functionality that modifies the contents of a phar, the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable must be off in order to succeed. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Throws [BadMethodCallException](class.badmethodcallexception) if the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable is on, the [zlib](https://www.php.net/manual/en/ref.zlib.php) extension is not available, or if any files are compressed using bzip2 compression and the [bzip2](https://www.php.net/manual/en/ref.bzip2.php) extension is not enabled. ### Examples **Example #1 A **Phar::decompressFiles()** example** ``` <?php $p = new Phar('/path/to/my.phar', 0, 'my.phar'); $p['myfile.txt'] = 'hi'; $p['myfile2.txt'] = 'hi'; $p->compressFiles(Phar::GZ); foreach ($p as $file) {     var_dump($file->getFileName());     var_dump($file->isCompressed());     var_dump($file->isCompressed(Phar::BZ2));     var_dump($file->isCompressed(Phar::GZ)); } $p->decompressFiles(); foreach ($p as $file) {     var_dump($file->getFileName());     var_dump($file->isCompressed());     var_dump($file->isCompressed(Phar::BZ2));     var_dump($file->isCompressed(Phar::GZ)); } ?> ``` The above example will output: ``` string(10) "myfile.txt" int(4096) bool(false) bool(true) string(11) "myfile2.txt" int(4096) bool(false) bool(true) string(10) "myfile.txt" bool(false) bool(false) bool(false) string(11) "myfile2.txt" bool(false) bool(false) bool(false) ``` ### See Also * [PharFileInfo::getCompressedSize()](pharfileinfo.getcompressedsize) - Returns the actual size of the file (with compression) inside the Phar archive * [PharFileInfo::isCompressed()](pharfileinfo.iscompressed) - Returns whether the entry is compressed * [PharFileInfo::compress()](pharfileinfo.compress) - Compresses the current Phar entry with either zlib or bzip2 compression * [PharFileInfo::decompress()](pharfileinfo.decompress) - Decompresses the current Phar entry within the phar * [Phar::canCompress()](phar.cancompress) - Returns whether phar extension supports compression using either zlib or bzip2 * [Phar::isCompressed()](phar.iscompressed) - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on) * [Phar::compressFiles()](phar.compressfiles) - Compresses all files in the current Phar archive * [Phar::getSupportedCompression()](phar.getsupportedcompression) - Return array of supported compression algorithms * [Phar::compress()](phar.compress) - Compresses the entire Phar archive using Gzip or Bzip2 compression * [Phar::decompress()](phar.decompress) - Decompresses the entire Phar archive php date_timestamp_set date\_timestamp\_set ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) date\_timestamp\_set — Alias of [DateTime::setTimestamp()](datetime.settimestamp) ### Description This function is an alias of: [DateTime::setTimestamp()](datetime.settimestamp) php pg_field_num pg\_field\_num ============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_field\_num — Returns the field number of the named field ### Description ``` pg_field_num(PgSql\Result $result, string $field): int ``` **pg\_field\_num()** will return the number of the field number that corresponds to the `field` in the given `result` instance. > > **Note**: > > > This function used to be called **pg\_fieldnum()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `field` The name of the field. The given name is treated like an identifier in an SQL command, that is, it is downcased unless double-quoted. ### Return Values The field number (numbered from 0), or -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting information about fields** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   $res = pg_query($dbconn, "select author, year, title from authors where author = 'Orwell'");      echo "Column 'title' is field number: ", pg_field_num($res, 'title'); ?> ``` The above example will output: ``` Column 'title' is field number: 2 ``` ### See Also * [pg\_field\_name()](function.pg-field-name) - Returns the name of a field php substr substr ====== (PHP 4, PHP 5, PHP 7, PHP 8) substr — Return part of a string ### Description ``` substr(string $string, int $offset, ?int $length = null): string ``` Returns the portion of `string` specified by the `offset` and `length` parameters. ### Parameters `string` The input string. `offset` If `offset` is non-negative, the returned string will start at the `offset`'th position in `string`, counting from zero. For instance, in the string '`abcdef`', the character at position `0` is '`a`', the character at position `2` is '`c`', and so forth. If `offset` is negative, the returned string will start at the `offset`'th character from the end of `string`. If `string` is less than `offset` characters long, an empty string will be returned. **Example #1 Using a negative `offset`** ``` <?php $rest = substr("abcdef", -1);    // returns "f" $rest = substr("abcdef", -2);    // returns "ef" $rest = substr("abcdef", -3, 1); // returns "d" ?> ``` `length` If `length` is given and is positive, the string returned will contain at most `length` characters beginning from `offset` (depending on the length of `string`). If `length` is given and is negative, then that many characters will be omitted from the end of `string` (after the start position has been calculated when a `offset` is negative). If `offset` denotes the position of this truncation or beyond, an empty string will be returned. If `length` is given and is `0`, an empty string will be returned. If `length` is omitted or **`null`**, the substring starting from `offset` until the end of the string will be returned. **Example #2 Using a negative `length`** ``` <?php $rest = substr("abcdef", 0, -1);  // returns "abcde" $rest = substr("abcdef", 2, -1);  // returns "cde" $rest = substr("abcdef", 4, -4);  // returns ""; prior to PHP 8.0.0, false was returned $rest = substr("abcdef", -3, -1); // returns "de" ?> ``` ### Return Values Returns the extracted part of `string`, or an empty string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `length` is nullable now. When `length` is explicitly set to **`null`**, the function returns a substring finishing at the end of the string, when it previously returned an empty string. | | 8.0.0 | The function returns an empty string where it previously returned **`false`**. | ### Examples **Example #3 Basic **substr()** usage** ``` <?php echo substr('abcdef', 1);     // bcdef echo substr("abcdef", 1, null); // bcdef; prior to PHP 8.0.0, empty string was returned echo substr('abcdef', 1, 3);  // bcd echo substr('abcdef', 0, 4);  // abcd echo substr('abcdef', 0, 8);  // abcdef echo substr('abcdef', -1, 1); // f // Accessing single characters in a string // can also be achieved using "square brackets" $string = 'abcdef'; echo $string[0];                 // a echo $string[3];                 // d echo $string[strlen($string)-1]; // f ?> ``` **Example #4 **substr()** casting behaviour** ``` <?php class apple {     public function __toString() {         return "green";     } } echo "1) ".var_export(substr("pear", 0, 2), true).PHP_EOL; echo "2) ".var_export(substr(54321, 0, 2), true).PHP_EOL; echo "3) ".var_export(substr(new apple(), 0, 2), true).PHP_EOL; echo "4) ".var_export(substr(true, 0, 1), true).PHP_EOL; echo "5) ".var_export(substr(false, 0, 1), true).PHP_EOL; echo "6) ".var_export(substr("", 0, 1), true).PHP_EOL; echo "7) ".var_export(substr(1.2e3, 0, 4), true).PHP_EOL; ?> ``` The above example will output: ``` 1) 'pe' 2) '54' 3) 'gr' 4) '1' 5) '' 6) '' 7) '1200' ``` **Example #5 Invalid Character Range** If an invalid character range is requested, **substr()** returns an empty string as of PHP 8.0.0; previously, **`false`** was returned instead. ``` <?php var_dump(substr('a', 2)); ?> ``` Output of the above example in PHP 8: ``` string(0) "" ``` ] Output of the above example in PHP 7: ``` bool(false) ``` ### See Also * [strrchr()](function.strrchr) - Find the last occurrence of a character in a string * [substr\_replace()](function.substr-replace) - Replace text within a portion of a string * [preg\_match()](function.preg-match) - Perform a regular expression match * [trim()](function.trim) - Strip whitespace (or other characters) from the beginning and end of a string * [mb\_substr()](function.mb-substr) - Get part of string * [wordwrap()](function.wordwrap) - Wraps a string to a given number of characters * [String access and modification by character](language.types.string#language.types.string.substr)
programming_docs
php jdmonthname jdmonthname =========== (PHP 4, PHP 5, PHP 7, PHP 8) jdmonthname — Returns a month name ### Description ``` jdmonthname(int $julian_day, int $mode): string ``` Returns a string containing a month name. `mode` tells this function which calendar to convert the Julian Day Count to, and what type of month names are to be returned. **Calendar modes**| Mode | Meaning | Values | | --- | --- | --- | | **`CAL_MONTH_GREGORIAN_SHORT`** | Gregorian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec | | **`CAL_MONTH_GREGORIAN_LONG`** | Gregorian | January, February, March, April, May, June, July, August, September, October, November, December | | **`CAL_MONTH_JULIAN_SHORT`** | Julian - abbreviated | Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec | | **`CAL_MONTH_JULIAN_LONG`** | Julian | January, February, March, April, May, June, July, August, September, October, November, December | | **`CAL_MONTH_JEWISH`** | Jewish | Tishri, Heshvan, Kislev, Tevet, Shevat, AdarI, AdarII, Nisan, Iyyar, Sivan, Tammuz, Av, Elul | | **`CAL_MONTH_FRENCH`** | French Republican | Vendemiaire, Brumaire, Frimaire, Nivose, Pluviose, Ventose, Germinal, Floreal, Prairial, Messidor, Thermidor, Fructidor, Extra | ### Parameters `jday` The Julian Day to operate on `mode` The calendar mode (see table above). ### Return Values The month name for the given Julian Day and `mode`. php Yaf_Config_Ini::offsetUnset Yaf\_Config\_Ini::offsetUnset ============================= (Yaf >=1.0.0) Yaf\_Config\_Ini::offsetUnset — The offsetUnset purpose ### Description ``` public Yaf_Config_Ini::offsetUnset(string $name): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php memory_reset_peak_usage memory\_reset\_peak\_usage ========================== (PHP 8 >= 8.2.0) memory\_reset\_peak\_usage — Reset the peak memory usage ### Description ``` memory_reset_peak_usage(): void ``` Resets the peak memory usage returned by the [memory\_get\_peak\_usage()](function.memory-get-peak-usage) function. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **memory\_reset\_peak\_usage()** example** ``` <?php var_dump(memory_get_peak_usage()); $a = str_repeat("Hello", 424242); var_dump(memory_get_peak_usage()); unset($a); memory_reset_peak_usage(); $a = str_repeat("Hello", 2424); var_dump(memory_get_peak_usage()); ?> ``` The above example will output something similar to: ``` int(422440) int(2508672) int(399208) ``` ### See Also * [memory\_get\_peak\_usage()](function.memory-get-peak-usage) - Returns the peak of memory allocated by PHP php pspell_config_runtogether pspell\_config\_runtogether =========================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_config\_runtogether — Consider run-together words as valid compounds ### Description ``` pspell_config_runtogether(PSpell\Config $config, bool $allow): bool ``` This function determines whether run-together words will be treated as legal compounds. That is, "thecat" will be a legal compound, although there should be a space between the two words. Changing this setting only affects the results returned by [pspell\_check()](function.pspell-check); [pspell\_suggest()](function.pspell-suggest) will still return suggestions. **pspell\_config\_runtogether()** should be used on a config before calling [pspell\_new\_config()](function.pspell-new-config). ### Parameters `config` An [PSpell\Config](class.pspell-config) instance. `allow` **`true`** if run-together words should be treated as legal compounds, **`false`** otherwise. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `config` parameter expects an [PSpell\Config](class.pspell-config) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pspell\_config\_runtogether()**** ``` <?php $pspell_config = pspell_config_create("en"); pspell_config_runtogether($pspell_config, true); $pspell = pspell_new_config($pspell_config); pspell_check($pspell, "thecat"); ?> ``` php Collator::getAttribute Collator::getAttribute ====================== collator\_get\_attribute ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Collator::getAttribute -- collator\_get\_attribute — Get collation attribute value ### Description Object-oriented style ``` public Collator::getAttribute(int $attribute): int|false ``` Procedural style ``` collator_get_attribute(Collator $object, int $attribute): int|false ``` Get a value of an integer collator attribute. ### Parameters `object` [Collator](class.collator) object. `attribute` Attribute to get value for. ### Return Values Attribute value, or **`false`** on failure. ### Examples **Example #1 **collator\_get\_attribute()** example** ``` <?php $coll = collator_create( 'en_CA' ); $val = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION ); if( $val === false ) {     // Handle error. } ?> ``` ### See Also * [[Collator](class.collator) constants](class.collator#intl.collator-constants) * [collator\_set\_attribute()](collator.setattribute) - Set collation attribute * [collator\_get\_strength()](collator.getstrength) - Get current collation strength php SplPriorityQueue::rewind SplPriorityQueue::rewind ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::rewind — Rewind iterator back to the start (no-op) ### Description ``` public SplPriorityQueue::rewind(): void ``` This rewinds the iterator to the beginning. This is a no-op for heaps as the iterator is virtual and in fact never moves from the top of the heap. ### Parameters This function has no parameters. ### Return Values No value is returned. php Imagick::current Imagick::current ================ (PECL imagick 2, PECL imagick 3) Imagick::current — Returns a reference to the current Imagick object ### Description ``` public Imagick::current(): Imagick ``` Returns reference to the current imagick object with image pointer at the correct sequence. ### Parameters This function has no parameters. ### Return Values Returns self on success. ### Errors/Exceptions Throws ImagickException on error. php sqlsrv_configure sqlsrv\_configure ================= (No version information available, might only be in Git) sqlsrv\_configure — Changes the driver error handling and logging configurations ### Description ``` sqlsrv_configure(string $setting, mixed $value): bool ``` Changes the driver error handling and logging configurations. ### Parameters `setting` The name of the setting to set. The possible values are "WarningsReturnAsErrors", "LogSubsystems", and "LogSeverity". `value` The value of the specified setting. The following table shows possible values: **Error and Logging Setting Options**| Setting | Options | | --- | --- | | WarningsReturnAsErrors | 1 (**`true`**) or 0 (**`false`**) | | LogSubsystems | SQLSRV\_LOG\_SYSTEM\_ALL (-1) SQLSRV\_LOG\_SYSTEM\_CONN (2) SQLSRV\_LOG\_SYSTEM\_INIT (1) SQLSRV\_LOG\_SYSTEM\_OFF (0) SQLSRV\_LOG\_SYSTEM\_STMT (4) SQLSRV\_LOG\_SYSTEM\_UTIL (8) | | LogSeverity | SQLSRV\_LOG\_SEVERITY\_ALL (-1) SQLSRV\_LOG\_SEVERITY\_ERROR (1) SQLSRV\_LOG\_SEVERITY\_NOTICE (4) SQLSRV\_LOG\_SEVERITY\_WARNING (2) | ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [» SQLSRV Error Handling](http://msdn.microsoft.com/en-us/library/cc626302.aspx). * [» Logging SQLSRV Activity](http://msdn.microsoft.com/en-us/library/cc296188.aspx). php hrtime hrtime ====== (PHP 7 >= 7.3.0, PHP 8) hrtime — Get the system's high resolution time ### Description ``` hrtime(bool $as_number = false): array|int|float|false ``` Returns the system's high resolution time, counted from an arbitrary point in time. The delivered timestamp is monotonic and can not be adjusted. ### Parameters `as_number` Whether the high resolution time should be returned as array or number. ### Return Values Returns an array of integers in the form [seconds, nanoseconds], if the parameter `as_number` is false. Otherwise the nanoseconds are returned as int (64bit platforms) or float (32bit platforms). Returns **`false`** on failure. ### Examples **Example #1 **hrtime()** usage** ``` <?php echo hrtime(true), PHP_EOL; print_r(hrtime()); ?> ``` The above example will output something similar to: ``` 10444739687370679 Array ( [0] => 10444739 [1] => 687464812 ) ``` ### See Also * The [High resolution timing](https://www.php.net/manual/en/book.hrtime.php) extension * [microtime()](function.microtime) - Return current Unix timestamp with microseconds php dio_write dio\_write ========== (PHP 4 >= 4.2.0, PHP 5 < 5.1.0) dio\_write — Writes data to fd with optional truncation at length ### Description ``` dio_write(resource $fd, string $data, int $len = 0): int ``` **dio\_write()** writes up to `len` bytes from `data` to file `fd`. ### Parameters `fd` The file descriptor returned by [dio\_open()](function.dio-open). `data` The written data. `len` The length of data to write in bytes. If not specified, the function writes all the data to the specified file. ### Return Values Returns the number of bytes written to `fd`. ### See Also * [dio\_read()](function.dio-read) - Reads bytes from a file descriptor php Ds\Set::reduce Ds\Set::reduce ============== (PECL ds >= 1.0.0) Ds\Set::reduce — Reduces the set to a single value using a callback function ### Description ``` public Ds\Set::reduce(callable $callback, mixed $initial = ?): mixed ``` Reduces the set to a single value using a callback function. ### Parameters `callback` ``` callback(mixed $carry, mixed $value): mixed ``` `carry` The return value of the previous callback, or `initial` if it's the first iteration. `value` The value of the current iteration. `initial` The initial value of the carry value. Can be **`null`**. ### Return Values The return value of the final callback. ### Examples **Example #1 **Ds\Set::reduce()** with initial value example** ``` <?php $set = new \Ds\Set([1, 2, 3]); $callback = function($carry, $value) {     return $carry * $value; }; var_dump($set->reduce($callback, 5)); // Iterations: // // $carry = $initial = 5 // // $carry = $carry * 1 =  5 // $carry = $carry * 2 = 10 // $carry = $carry * 3 = 30 ?> ``` The above example will output something similar to: ``` int(30) ``` **Example #2 **Ds\Set::reduce()** without an initial value example** ``` <?php $set = new \Ds\Set([1, 2, 3]); var_dump($set->reduce(function($carry, $value) {     return $carry + $value + 5; })); // Iterations: // // $carry = $initial = null // // $carry = $carry + 1 + 5 =  6 // $carry = $carry + 2 + 5 = 13 // $carry = $carry + 3 + 5 = 21 ?> ``` The above example will output something similar to: ``` int(21) ``` php Gmagick::setimageprofile Gmagick::setimageprofile ======================== (PECL gmagick >= Unknown) Gmagick::setimageprofile — Adds a named profile to the Gmagick object ### Description ``` public Gmagick::setimageprofile(string $name, string $profile): Gmagick ``` Adds a named profile to the Gmagick object. If a profile with the same name already exists, it is replaced. This method differs from the Gmagick::profileimage() method in that it does not apply any CMS color profiles. ### Parameters `name` Name of profile to add or remove: ICC, IPTC, or generic profile. `profile` The profile. ### Return Values The Gmagick object on success. ### Errors/Exceptions Throws an **GmagickException** on error. php iterator_apply iterator\_apply =============== (PHP 5 >= 5.1.0, PHP 7, PHP 8) iterator\_apply — Call a function for every element in an iterator ### Description ``` iterator_apply(Traversable $iterator, callable $callback, ?array $args = null): int ``` Calls a function for every element in an iterator. ### Parameters `iterator` The iterator object to iterate over. `callback` The callback function to call on every element. This function only receives the given `args`, so it is nullary by default. If `count($args) === 3`, for instance, the callback function is ternary. > **Note**: The function must return **`true`** in order to continue iterating over the `iterator`. > > `args` An array of arguments; each element of `args` is passed to the callback `callback` as separate argument. ### Return Values Returns the iteration count. ### Examples **Example #1 **iterator\_apply()** example** ``` <?php function print_caps(Iterator $iterator) {     echo strtoupper($iterator->current()) . "\n";     return TRUE; } $it = new ArrayIterator(array("Apples", "Bananas", "Cherries")); iterator_apply($it, "print_caps", array($it)); ?> ``` The above example will output: ``` APPLES BANANAS CHERRIES ``` ### See Also * [array\_walk()](function.array-walk) - Apply a user supplied function to every member of an array php svn_fs_revision_prop svn\_fs\_revision\_prop ======================= (PECL svn >= 0.1.0) svn\_fs\_revision\_prop — Fetches the value of a named property ### Description ``` svn_fs_revision_prop(resource $fs, int $revnum, string $propname): string ``` **Warning**This function is currently not documented; only its argument list is available. Fetches the value of a named property ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php eio_custom eio\_custom =========== (PECL eio >= 0.0.1dev) eio\_custom — Execute custom request like any other *eio\_\** call ### Description ``` eio_custom( callable $execute, int $pri, callable $callback, mixed $data = NULL ): resource ``` **eio\_custom()** executes custom function specified by `execute` processing it just like any other *eio\_\** call. ### Parameters `execute` Specifies the request function that should match the following prototype: ``` mixed execute(mixed data); ``` `callback` is event completion callback that should match the following prototype: ``` void callback(mixed data, mixed result); ``` `data` is the data passed to `execute` via `data` argument without modifications `result` value returned by `execute` `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_custom()** returns request resource on success, or **`false`** on failure. ### Examples **Example #1 **eio\_custom()** example** ``` <?php /* Callback for the custom callback */ function my_custom_callback($data, $result) {     var_dump($data);     var_dump(count($result));     var_dump($result['data_modified']);     var_dump($result['result']); } /* The custom request */ function my_custom($data) {     var_dump($data);     $result  = array(         'result'        => 1001,         'data_modified' => "my custom data",     );     return $result; } $data = "my_custom_data"; $req = eio_custom("my_custom", EIO_PRI_DEFAULT, "my_custom_callback", $data); var_dump($req); eio_event_loop(); ?> ``` The above example will output something similar to: ``` resource(4) of type (EIO Request Descriptor) string(14) "my_custom_data" string(14) "my_custom_data" int(2) string(14) "my custom data" int(1001) ``` php Componere\Patch::apply Componere\Patch::apply ====================== (Componere 2 >= 2.1.0) Componere\Patch::apply — Application ### Description ``` public Componere\Patch::apply(): void ``` Shall apply the current patch php stream_notification_callback stream\_notification\_callback ============================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) stream\_notification\_callback — A callback function for the `notification` context parameter ### Description ``` stream_notification_callback( int $notification_code, int $severity, string $message, int $message_code, int $bytes_transferred, int $bytes_max ): void ``` A [callable](language.types.callable) function, used by the [notification context parameter](https://www.php.net/manual/en/context.params.php#context.params.notification), called during an event. > > **Note**: > > > This is *not* a real function, only a prototype of how the function should be. > > ### Parameters `notification_code` One of the **`STREAM_NOTIFY_*`** notification constants. `severity` One of the **`STREAM_NOTIFY_SEVERITY_*`** notification constants. `message` Passed if a descriptive message is available for the event. `message_code` Passed if a descriptive message code is available for the event. The meaning of this value is dependent on the specific wrapper in use. `bytes_transferred` If applicable, the `bytes_transferred` will be populated. `bytes_max` If applicable, the `bytes_max` will be populated. ### Return Values No value is returned. ### Examples **Example #1 **stream\_notification\_callback()** example** ``` <?php function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {     switch($notification_code) {         case STREAM_NOTIFY_RESOLVE:         case STREAM_NOTIFY_AUTH_REQUIRED:         case STREAM_NOTIFY_COMPLETED:         case STREAM_NOTIFY_FAILURE:         case STREAM_NOTIFY_AUTH_RESULT:             var_dump($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max);             /* Ignore */             break;         case STREAM_NOTIFY_REDIRECTED:             echo "Being redirected to: ", $message;             break;         case STREAM_NOTIFY_CONNECT:             echo "Connected...";             break;         case STREAM_NOTIFY_FILE_SIZE_IS:             echo "Got the filesize: ", $bytes_max;             break;         case STREAM_NOTIFY_MIME_TYPE_IS:             echo "Found the mime-type: ", $message;             break;         case STREAM_NOTIFY_PROGRESS:             echo "Made some progress, downloaded ", $bytes_transferred, " so far";             break;     }     echo "\n"; } $ctx = stream_context_create(); stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); file_get_contents("http://php.net/contact", false, $ctx); ?> ``` The above example will output something similar to: ``` Connected... Found the mime-type: text/html; charset=utf-8 Being redirected to: http://no.php.net/contact Connected... Got the filesize: 0 Found the mime-type: text/html; charset=utf-8 Being redirected to: http://no.php.net/contact.php Connected... Got the filesize: 4589 Found the mime-type: text/html;charset=utf-8 Made some progress, downloaded 0 so far Made some progress, downloaded 0 so far Made some progress, downloaded 0 so far Made some progress, downloaded 1440 so far Made some progress, downloaded 2880 so far Made some progress, downloaded 4320 so far Made some progress, downloaded 5760 so far Made some progress, downloaded 6381 so far Made some progress, downloaded 7002 so far ``` **Example #2 Simple progressbar for commandline download client** ``` <?php function usage($argv) {     echo "Usage:\n";     printf("\tphp %s <http://example.com/file> <localfile>\n", $argv[0]);     exit(1); } function stream_notification_callback($notification_code, $severity, $message, $message_code, $bytes_transferred, $bytes_max) {     static $filesize = null;     switch($notification_code) {     case STREAM_NOTIFY_RESOLVE:     case STREAM_NOTIFY_AUTH_REQUIRED:     case STREAM_NOTIFY_COMPLETED:     case STREAM_NOTIFY_FAILURE:     case STREAM_NOTIFY_AUTH_RESULT:         /* Ignore */         break;     case STREAM_NOTIFY_REDIRECTED:         echo "Being redirected to: ", $message, "\n";         break;     case STREAM_NOTIFY_CONNECT:         echo "Connected...\n";         break;     case STREAM_NOTIFY_FILE_SIZE_IS:         $filesize = $bytes_max;         echo "Filesize: ", $filesize, "\n";         break;     case STREAM_NOTIFY_MIME_TYPE_IS:         echo "Mime-type: ", $message, "\n";         break;     case STREAM_NOTIFY_PROGRESS:         if ($bytes_transferred > 0) {             if (!isset($filesize)) {                 printf("\rUnknown filesize.. %2d kb done..", $bytes_transferred/1024);             } else {                 $length = (int)(($bytes_transferred/$filesize)*100);                 printf("\r[%-100s] %d%% (%2d/%2d kb)", str_repeat("=", $length). ">", $length, ($bytes_transferred/1024), $filesize/1024);             }         }         break;     } } isset($argv[1], $argv[2]) or usage($argv); $ctx = stream_context_create(); stream_context_set_params($ctx, array("notification" => "stream_notification_callback")); $fp = fopen($argv[1], "r", false, $ctx); if (is_resource($fp) && file_put_contents($argv[2], $fp)) {     echo "\nDone!\n";     exit(0); } $err = error_get_last(); echo "\nErrrrrorr..\n", $err["message"], "\n"; exit(1); ?> ``` Executing the example above with: `php -n fetch.php http://no2.php.net/get/php-5-LATEST.tar.bz2/from/this/mirror php-latest.tar.bz2` will output something similar too: ``` Connected... Mime-type: text/html; charset=utf-8 Being redirected to: http://no2.php.net/distributions/php-5.2.5.tar.bz2 Connected... Filesize: 7773024 Mime-type: application/octet-stream [========================================> ] 40% (3076/7590 kb) ``` ### See Also * [Context parameters](https://www.php.net/manual/en/context.params.php)
programming_docs
php imap_getacl imap\_getacl ============ (PHP 5, PHP 7, PHP 8) imap\_getacl — Gets the ACL for a given mailbox ### Description ``` imap_getacl(IMAP\Connection $imap, string $mailbox): array|false ``` Gets the ACL for a given mailbox. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `mailbox` The mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. ### Return Values Returns an associative array of "folder" => "acl" pairs, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_getacl()** example** ``` <?php print_r(imap_getacl($imap, 'user.joecool')); ?> ``` The above example will output something similar to: ``` Array ( [asubfolder] => lrswipcda [anothersubfolder] => lrswipcda ) ``` ### Notes This function is currently only available to users of the c-client2000 or greater library. ### See Also * [imap\_setacl()](function.imap-setacl) - Sets the ACL for a given mailbox php Ds\Deque::get Ds\Deque::get ============= (PECL ds >= 1.0.0) Ds\Deque::get — Returns the value at a given index ### Description ``` public Ds\Deque::get(int $index): mixed ``` Returns the value at a given index. ### Parameters `index` The index to access, starting at 0. ### Return Values The value at the requested index. ### Errors/Exceptions [OutOfRangeException](class.outofrangeexception) if the index is not valid. ### Examples **Example #1 **Ds\Deque::get()** example** ``` <?php $deque = new \Ds\Deque(["a", "b", "c"]); var_dump($deque->get(0)); var_dump($deque->get(1)); var_dump($deque->get(2)); ?> ``` The above example will output something similar to: ``` string(1) "a" string(1) "b" string(1) "c" ``` **Example #2 **Ds\Deque::get()** example using array syntax** ``` <?php $deque = new \Ds\Deque(["a", "b", "c"]); var_dump($deque[0]); var_dump($deque[1]); var_dump($deque[2]); ?> ``` The above example will output something similar to: ``` string(1) "a" string(1) "b" string(1) "c" ``` php The Ev class The Ev class ============ Introduction ------------ (PECL ev >= 0.2.0) Ev is a static class providing access to the default loop and to some common operations. Class synopsis -------------- final class **Ev** { /\* Constants \*/ const int [FLAG\_AUTO](class.ev#ev.constants.flag-auto) = 0; const int [FLAG\_NOENV](class.ev#ev.constants.flag-noenv) = 16777216; const int [FLAG\_FORKCHECK](class.ev#ev.constants.flag-forkcheck) = 33554432; const int [FLAG\_NOINOTIFY](class.ev#ev.constants.flag-noinotify) = 1048576; const int [FLAG\_SIGNALFD](class.ev#ev.constants.flag-signalfd) = 2097152; const int [FLAG\_NOSIGMASK](class.ev#ev.constants.flag-nosigmask) = 4194304; const int [RUN\_NOWAIT](class.ev#ev.constants.run-nowait) = 1; const int [RUN\_ONCE](class.ev#ev.constants.run-once) = 2; const int [BREAK\_CANCEL](class.ev#ev.constants.break-cancel) = 0; const int [BREAK\_ONE](class.ev#ev.constants.break-one) = 1; const int [BREAK\_ALL](class.ev#ev.constants.break-all) = 2; const int [MINPRI](class.ev#ev.constants.minpri) = -2; const int [MAXPRI](class.ev#ev.constants.maxpri) = 2; const int [READ](class.ev#ev.constants.read) = 1; const int [WRITE](class.ev#ev.constants.write) = 2; const int [TIMER](class.ev#ev.constants.timer) = 256; const int [PERIODIC](class.ev#ev.constants.periodic) = 512; const int [SIGNAL](class.ev#ev.constants.signal) = 1024; const int [CHILD](class.ev#ev.constants.child) = 2048; const int [STAT](class.ev#ev.constants.stat) = 4096; const int [IDLE](class.ev#ev.constants.idle) = 8192; const int [PREPARE](class.ev#ev.constants.prepare) = 16384; const int [CHECK](class.ev#ev.constants.check) = 32768; const int [EMBED](class.ev#ev.constants.embed) = 65536; const int [CUSTOM](class.ev#ev.constants.custom) = 16777216; const int [ERROR](class.ev#ev.constants.error) = 2147483648; const int [BACKEND\_SELECT](class.ev#ev.constants.backend-select) = 1; const int [BACKEND\_POLL](class.ev#ev.constants.backend-poll) = 2; const int [BACKEND\_EPOLL](class.ev#ev.constants.backend-epoll) = 4; const int [BACKEND\_KQUEUE](class.ev#ev.constants.backend-kqueue) = 8; const int [BACKEND\_DEVPOLL](class.ev#ev.constants.backend-devpoll) = 16; const int [BACKEND\_PORT](class.ev#ev.constants.backend-port) = 32; const int [BACKEND\_ALL](class.ev#ev.constants.backend-all) = 63; const int [BACKEND\_MASK](class.ev#ev.constants.backend-mask) = 65535; /\* Methods \*/ ``` final public static backend(): int ``` ``` final public static depth(): int ``` ``` final public static embeddableBackends(): int ``` ``` final public static feedSignal( int $signum ): void ``` ``` final public static feedSignalEvent( int $signum ): void ``` ``` final public static iteration(): int ``` ``` final public static now(): float ``` ``` final public static nowUpdate(): void ``` ``` final public static recommendedBackends(): int ``` ``` final public static resume(): void ``` ``` final public static run( int $flags = ?): void ``` ``` final public static sleep( float $seconds ): void ``` ``` final public static stop( int $how = ?): void ``` ``` final public static supportedBackends(): int ``` ``` final public static suspend(): void ``` ``` final public static time(): float ``` ``` final public static verify(): void ``` } Predefined Constants -------------------- Flags passed to create a loop: **`Ev::FLAG_AUTO`** The default flags value **`Ev::FLAG_NOENV`** If this flag used(or the program runs setuid or setgid), `libev` won't look at the environment variable LIBEV\_FLAGS . Otherwise(by default), LIBEV\_FLAGS will override the flags completely if it is found. Useful for performance tests and searching for bugs. **`Ev::FLAG_FORKCHECK`** Makes libev check for a fork in each iteration, instead of calling [EvLoop::fork()](evloop.fork) manually. This works by calling `getpid()` on every iteration of the loop, and thus this might slow down the event loop with lots of loop iterations, but usually is not noticeable. This flag setting cannot be overridden or specified in the LIBEV\_FLAGS environment variable. **`Ev::FLAG_NOINOTIFY`** When this flag is specified, `libev` won't attempt to use the `inotify` API for its [» ev\_stat](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_stat_code_did_the_file_attri) watchers. The flag can be useful to conserve inotify file descriptors, as otherwise each loop using `ev_stat` watchers consumes one `inotify` handle. **`Ev::FLAG_SIGNALFD`** When this flag is specified, `libev` will attempt to use the `signalfd` API for its [» ev\_signal](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_signal_code_signal_me_when_a) (and [» ev\_child](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#code_ev_child_code_watch_out_for_pro) ) watchers. This API delivers signals synchronously, which makes it both faster and might make it possible to get the queued signal data. It can also simplify signal handling with threads, as long as signals are properly blocked in threads. `Signalfd` will not be used by default. **`Ev::FLAG_NOSIGMASK`** When this flag is specified, `libev` will avoid to modify the signal mask. Specifically, this means having to make sure signals are unblocked before receiving them. This behaviour is useful for custom signal handling, or handling signals only in specific threads. Flags passed to [Ev::run()](ev.run) , or [EvLoop::run()](evloop.run) **`Ev::RUN_NOWAIT`** Means that event loop will look for new events, will handle those events and any already outstanding ones, but will not wait and block the process in case there are no events and will return after one iteration of the loop. This is sometimes useful to poll and handle new events while doing lengthy calculations, to keep the program responsive. **`Ev::RUN_ONCE`** Means that event loop will look for new events (waiting if necessary) and will handle those and any already outstanding ones. It will block the process until at least one new event arrives (which could be an event internal to libev itself, so there is no guarantee that a user-registered callback will be called), and will return after one iteration of the loop. Flags passed to [Ev::stop()](ev.stop) , or [EvLoop::stop()](evloop.stop) **`Ev::BREAK_CANCEL`** Cancel the break operation. **`Ev::BREAK_ONE`** Makes the innermost [Ev::run()](ev.run) (or [EvLoop::run()](evloop.run) ) call return. **`Ev::BREAK_ALL`** Makes all nested [Ev::run()](ev.run) (or [EvLoop::run()](evloop.run) ) calls return. Watcher priorities: **`Ev::MINPRI`** Minimum allowed watcher priority. **`Ev::MAXPRI`** Maximum allowed watcher priority. Bit masks of (received) events: **`Ev::READ`** The file descriptor in the [EvIo](class.evio) watcher has become readable. **`Ev::WRITE`** The file descriptor in the [EvIo](class.evio) watcher has become writable. **`Ev::TIMER`** [EvTimer](class.evtimer) watcher has been timed out. **`Ev::PERIODIC`** [EvPeriodic](class.evperiodic) watcher has been timed out. **`Ev::SIGNAL`** A signal specified in [EvSignal::\_\_construct()](evsignal.construct) has been received. **`Ev::CHILD`** The `pid` specified in [EvChild::\_\_construct()](evchild.construct) has received a status change. **`Ev::STAT`** The path specified in [EvStat](class.evstat) watcher changed its attributes. **`Ev::IDLE`** [EvIdle](class.evidle) watcher works when there is nothing to do with other watchers. **`Ev::PREPARE`** All [EvPrepare](class.evprepare) watchers are invoked just before [Ev::run()](ev.run) starts. Thus, [EvPrepare](class.evprepare) watchers are the last watchers invoked before the event loop sleeps or polls for new events. **`Ev::CHECK`** All [EvCheck](class.evcheck) watchers are queued just after [Ev::run()](ev.run) has gathered the new events, but before it queues any callbacks for any received events. Thus, [EvCheck](class.evcheck) watchers will be invoked before any other watchers of the same or lower priority within an event loop iteration. **`Ev::EMBED`** The embedded event loop specified in the [EvEmbed](class.evembed) watcher needs attention. **`Ev::CUSTOM`** Not ever sent(or otherwise used) by `libev` itself, but can be freely used by `libev` users to signal watchers (e.g. via [EvWatcher::feed()](evwatcher.feed) ). **`Ev::ERROR`** An unspecified error has occurred, the watcher has been stopped. This might happen because the watcher could not be properly started because `libev` ran out of memory, a file descriptor was found to be closed or any other problem. `Libev` considers these application bugs. See also [» ANATOMY OF A WATCHER](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#ANATOMY_OF_A_WATCHER_CONTENT) Backend flags: **`Ev::BACKEND_SELECT`** `select(2) backend` **`Ev::BACKEND_POLL`** `poll(2) backend` **`Ev::BACKEND_EPOLL`** Linux-specific `epoll(7)` backend for both pre- and post-2.6.9 kernels **`Ev::BACKEND_KQUEUE`** `kqueue` backend used on most BSD systems. [EvEmbed](class.evembed) watcher could be used to embed one loop(with kqueue backend) into another. For instance, one can try to create an event loop with `kqueue` backend and use it for sockets only. **`Ev::BACKEND_DEVPOLL`** Solaris 8 backend. This is not implemented yet. **`Ev::BACKEND_PORT`** Solaris 10 event port mechanism with a good scaling. **`Ev::BACKEND_ALL`** Try all backends(even currupted ones). It's not recommended to use it explicitly. Bitwise operators should be applied here(e.g. **`Ev::BACKEND_ALL`** & ~ **`Ev::BACKEND_KQUEUE`** ) Use [Ev::recommendedBackends()](ev.recommendedbackends) , or don't specify any backends at all. **`Ev::BACKEND_MASK`** Not a backend, but a mask to select all backend bits from `flags` value to mask out any backends(e.g. when modifying the LIBEV\_FLAGS environment variable). > > **Note**: > > > For the default loop during module initialization phase `Ev` registers [» ev\_loop\_fork](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#FUNCTIONS_CONTROLLING_EVENT_LOOPS_CO) call by means of `pthread_atfork` (if available). > > > > **Note**: > > > There are methods providing access to the *default event loop* in **Ev** class(e.g. [Ev::iteration()](ev.iteration) , [Ev::depth()](ev.depth) etc.) For *custom loops* (created with [EvLoop::\_\_construct()](evloop.construct) ) these values may be accessed via corresponding properties and methods of the [EvLoop](class.evloop) class. > > The instance of the default event loop itself can be fetched by means of [EvLoop::defaultLoop()](evloop.defaultloop) method. > > Table of Contents ----------------- * [Ev::backend](ev.backend) — Returns an integer describing the backend used by libev * [Ev::depth](ev.depth) — Returns recursion depth * [Ev::embeddableBackends](ev.embeddablebackends) — Returns the set of backends that are embeddable in other event loops * [Ev::feedSignal](ev.feedsignal) — Feed a signal event info Ev * [Ev::feedSignalEvent](ev.feedsignalevent) — Feed signal event into the default loop * [Ev::iteration](ev.iteration) — Return the number of times the default event loop has polled for new events * [Ev::now](ev.now) — Returns the time when the last iteration of the default event loop has started * [Ev::nowUpdate](ev.nowupdate) — Establishes the current time by querying the kernel, updating the time returned by Ev::now in the progress * [Ev::recommendedBackends](ev.recommendedbackends) — Returns a bit mask of recommended backends for current platform * [Ev::resume](ev.resume) — Resume previously suspended default event loop * [Ev::run](ev.run) — Begin checking for events and calling callbacks for the default loop * [Ev::sleep](ev.sleep) — Block the process for the given number of seconds * [Ev::stop](ev.stop) — Stops the default event loop * [Ev::supportedBackends](ev.supportedbackends) — Returns the set of backends supported by current libev configuration * [Ev::suspend](ev.suspend) — Suspend the default event loop * [Ev::time](ev.time) — Returns the current time in fractional seconds since the epoch * [Ev::verify](ev.verify) — Performs internal consistency checks(for debugging) php Imagick::adaptiveBlurImage Imagick::adaptiveBlurImage ========================== (PECL imagick 2, PECL imagick 3) Imagick::adaptiveBlurImage — Adds adaptive blur filter to image ### Description ``` public Imagick::adaptiveBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Adds an adaptive blur filter to image. The intensity of an adaptive blur depends is dramatically decreased at edge of the image, whereas a standard blur is uniform across the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `radius` The radius of the Gaussian, in pixels, not counting the center pixel. Provide a value of 0 and the radius will be chosen automagically. `sigma` The standard deviation of the Gaussian, in pixels. `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::adaptiveBlurImage()**:** Adaptively blur an image, then display to the browser. ``` <?php header('Content-type: image/jpeg'); $image = new Imagick('test.jpg'); $image->adaptiveBlurImage(5,3); echo $image; ?> ``` The above example will output something similar to: ### See Also * [Imagick::blurImage()](imagick.blurimage) - Adds blur filter to image * [Imagick::motionBlurImage()](imagick.motionblurimage) - Simulates motion blur * [Imagick::radialBlurImage()](imagick.radialblurimage) - Radial blurs an image php ImagickDraw::push ImagickDraw::push ================= (PECL imagick 2, PECL imagick 3) ImagickDraw::push — Clones the current ImagickDraw and pushes it to the stack ### Description ``` public ImagickDraw::push(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Clones the current ImagickDraw to create a new ImagickDraw, which is then added to the ImagickDraw stack. The original drawing ImagickDraw(s) may be returned to by invoking [ImagickDraw::pop()](imagickdraw.pop). The ImagickDraws are stored on a ImagickDraw stack. For every Pop there must have already been an equivalent Push. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ImagickDraw::push()** example** ``` <?php function push($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillModifiedColor);     $draw->setStrokeWidth(2);     $draw->setFontSize(72);     $draw->push();     $draw->translate(50, 50);     $draw->rectangle(200, 200, 300, 300);     $draw->pop();     $draw->setFillColor($fillColor);     $draw->rectangle(200, 200, 300, 300);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php Generator::valid Generator::valid ================ (PHP 5 >= 5.5.0, PHP 7, PHP 8) Generator::valid — Check if the iterator has been closed ### Description ``` public Generator::valid(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`false`** if the iterator has been closed. Otherwise returns **`true`**. php pg_lo_unlink pg\_lo\_unlink ============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_unlink — Delete a large object ### Description ``` pg_lo_unlink(PgSql\Connection $connection, int $oid): bool ``` **pg\_lo\_unlink()** deletes a large object with the `oid`. Returns **`true`** on success or **`false`** on failure. To use the large object interface, it is necessary to enclose it within a transaction block. > > **Note**: > > > This function used to be called **pg\_lounlink()**. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `oid` The OID of the large object in the database. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_unlink()** example** ``` <?php    // OID of the large object to delete    $doc_oid = 189762345;    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    pg_lo_unlink($database, $doc_oid);    pg_query($database, "commit"); ?> ``` ### See Also * [pg\_lo\_create()](function.pg-lo-create) - Create a large object * [pg\_lo\_import()](function.pg-lo-import) - Import a large object from file
programming_docs
php VarnishAdmin::setParam VarnishAdmin::setParam ====================== (PECL varnish >= 0.4) VarnishAdmin::setParam — Set configuration param on the current varnish instance ### Description ``` public VarnishAdmin::setParam(string $name, string|int $value): int ``` ### Parameters `name` Varnish configuration param name. `value` Varnish configuration param value. ### Return Values Returns the varnish command status. php log1p log1p ===== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) log1p — Returns log(1 + number), computed in a way that is accurate even when the value of number is close to zero ### Description ``` log1p(float $num): float ``` **log1p()** returns log(1 + `num`) computed in a way that is accurate even when the value of `num` is close to zero. [log()](function.log) might only return log(1) in this case due to lack of precision. ### Parameters `num` The argument to process ### Return Values log(1 + `num`) ### See Also * [expm1()](function.expm1) - Returns exp(number) - 1, computed in a way that is accurate even when the value of number is close to zero * [log()](function.log) - Natural logarithm * [log10()](function.log10) - Base-10 logarithm php GearmanJob::data GearmanJob::data ================ (PECL gearman <= 0.5.0) GearmanJob::data — Send data for a running job (deprecated) ### Description ``` public GearmanJob::data(string $data): bool ``` Sends data to the job server (and any listening clients) for this job. > > **Note**: > > > This method has been replaced by [GearmanJob::sendData()](gearmanjob.senddata) in the 0.6.0 release of the Gearman extension. > > ### Parameters `data` Arbitrary serialized data. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::workload()](gearmanjob.workload) - Get workload * [GearmanTask::data()](gearmantask.data) - Get data returned for a task php ZipArchive::addFile ZipArchive::addFile =================== (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::addFile — Adds a file to a ZIP archive from the given path ### Description ``` public ZipArchive::addFile( string $filepath, string $entryname = "", int $start = 0, int $length = 0, int $flags = ZipArchive::FL_OVERWRITE ): bool ``` Adds a file to a ZIP archive from a given path. > **Note**: For maximum portability, it is recommended to always use forward slashes (`/`) as directory separator in ZIP filenames. > > ### Parameters `filepath` The path to the file to add. `entryname` If supplied and not empty, this is the local name inside the ZIP archive that will override the `filepath`. `start` For partial copy, start position. `length` For partial copy, length to be copied, if 0 or -1 the whole file (starting from `start`) is used. `flags` Bitmask consisting of **`ZipArchive::FL_OVERWRITE`**, **`ZipArchive::FL_ENC_GUESS`**, **`ZipArchive::FL_ENC_UTF_8`**, **`ZipArchive::FL_ENC_CP437`**. The behaviour of these constants is described on the [ZIP constants](https://www.php.net/manual/en/zip.constants.php) page. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 / 1.18.0 | `flags` was added. | ### Examples This example opens a ZIP file archive test.zip and add the file /path/to/index.txt. as newname.txt. **Example #1 Open and add** ``` <?php $zip = new ZipArchive; if ($zip->open('test.zip') === TRUE) {     $zip->addFile('/path/to/index.txt', 'newname.txt');     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` ### Notes > > **Note**: > > > When a file is set to be added to the archive, PHP will lock the file. The lock is only released once the [ZipArchive](class.ziparchive) object has been closed, either via [ZipArchive::close()](ziparchive.close) or the [ZipArchive](class.ziparchive) object being destroyed. This may prevent you from being able to delete the file being added until after the lock has been released. > > ### See Also * [ZipArchive::replaceFile()](ziparchive.replacefile) - Replace file in ZIP archive with a given path php pg_set_client_encoding pg\_set\_client\_encoding ========================= (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) pg\_set\_client\_encoding — Set the client encoding ### Description ``` pg_set_client_encoding(PgSql\Connection $connection = ?, string $encoding): int ``` **pg\_set\_client\_encoding()** sets the client encoding and returns 0 if success or -1 if error. PostgreSQL will automatically convert data in the backend database encoding into the frontend encoding. > > **Note**: > > > The function used to be called **pg\_setclientencoding()**. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `encoding` The required client encoding. One of `SQL_ASCII`, `EUC_JP`, `EUC_CN`, `EUC_KR`, `EUC_TW`, `UNICODE`, `MULE_INTERNAL`, `LATINX` (X=1...9), `KOI8`, `WIN`, `ALT`, `SJIS`, `BIG5` or `WIN1250`. The exact list of available encodings depends on your PostgreSQL version, so check your PostgreSQL manual for a more specific list. ### Return Values Returns `0` on success or `-1` on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_set\_client\_encoding()** example** ``` <?php $conn = pg_pconnect("dbname=publisher"); if (!$conn) {   echo "An error occurred.\n";   exit; } // Set the client encoding to UNICODE.  Data will be automatically // converted from the backend encoding to the frontend. pg_set_client_encoding($conn, "UNICODE"); $result = pg_query($conn, "SELECT author, email FROM authors"); if (!$result) {   echo "An error occurred.\n";   exit; } // Write out UTF-8 data while ($row = pg_fetch_row($result)) {   echo "Author: $row[0]  E-mail: $row[1]";   echo "<br />\n"; }   ?> ``` ### See Also * [pg\_client\_encoding()](function.pg-client-encoding) - Gets the client encoding php eio_nop eio\_nop ======== (PECL eio >= 0.0.1dev) eio\_nop — Does nothing, except go through the whole request cycle ### Description ``` eio_nop(int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL): resource ``` **eio\_nop()** does nothing, except go through the whole request cycle. Could be useful in debugging. ### Parameters `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_nop()** returns request resource on success, or **`false`** on failure. ### See Also * [eio\_busy()](function.eio-busy) - Artificially increase load. Could be useful in tests, benchmarking php wincache_ucache_add wincache\_ucache\_add ===================== (PECL wincache >= 1.1.0) wincache\_ucache\_add — Adds a variable in user cache only if variable does not already exist in the cache ### Description ``` wincache_ucache_add(string $key, mixed $value, int $ttl = 0): bool ``` ``` wincache_ucache_add(array $values, mixed $unused = NULL, int $ttl = 0): bool ``` Adds a variable in user cache, only if this variable doesn't already exist in the cache. The added variable remains in the user cache unless its time to live expires or it is deleted by using [wincache\_ucache\_delete()](function.wincache-ucache-delete) or [wincache\_ucache\_clear()](function.wincache-ucache-clear) functions. ### Parameters `key` Store the variable using this `key` name. If a variable with same key is already present the function will fail and return **`false`**. `key` is case sensitive. To override the value even if `key` is present use [wincache\_ucache\_set()](function.wincache-ucache-set) function instad. `key` can also take array of name => value pairs where names will be used as keys. This can be used to add multiple values in the cache in one operation, thus avoiding race condition. `value` Value of a variable to store. `Value` supports all data types except resources, such as file handles. This paramter is ignored if first argument is an array. A general guidance is to pass **`null`** as `value` while using array as `key`. If `value` is an object, or an array containing objects, then the objects will be serialized. See [\_\_sleep()](language.oop5.magic#object.sleep) for details on serializing objects. `values` Associative array of keys and values. `ttl` Time for the variable to live in the cache in seconds. After the value specified in `ttl` has passed the stored variable will be deleted from the cache. This parameter takes a default value of `0` which means the variable will stay in the cache unless explicitly deleted by using [wincache\_ucache\_delete()](function.wincache-ucache-delete) or [wincache\_ucache\_clear()](function.wincache-ucache-clear) functions. ### Return Values If `key` is string, the function returns **`true`** on success and **`false`** on failure. If `key` is an array, the function returns: * If all the name => value pairs in the array can be set, function returns an empty array; * If all the name => value pairs in the array cannot be set, function returns **`false`**; * If some can be set while others cannot, function returns an array with name=>value pair for which the addition failed in the user cache. ### Examples **Example #1 **wincache\_ucache\_add()** with `key` as a string** ``` <?php $bar = 'BAR'; var_dump(wincache_ucache_add('foo', $bar)); var_dump(wincache_ucache_add('foo', $bar)); var_dump(wincache_ucache_get('foo')); ?> ``` The above example will output: ``` bool(true) bool(false) string(3) "BAR" ``` **Example #2 **wincache\_ucache\_add()** with `key` as an array** ``` <?php $colors_array = array('green' => '5', 'Blue' => '6', 'yellow' => '7', 'cyan' => '8'); var_dump(wincache_ucache_add($colors_array)); var_dump(wincache_ucache_add($colors_array)); var_dump(wincache_ucache_get('Blue')); ?> ``` The above example will output: ``` array(0) { } array(4) { ["green"]=> int(-1) ["Blue"]=> int(-1) ["yellow"]=> int(-1) ["cyan"]=> int(-1) } string(1) "6" ``` ### See Also * [wincache\_ucache\_set()](function.wincache-ucache-set) - Adds a variable in user cache and overwrites a variable if it already exists in the cache * [wincache\_ucache\_get()](function.wincache-ucache-get) - Gets a variable stored in the user cache * [wincache\_ucache\_delete()](function.wincache-ucache-delete) - Deletes variables from the user cache * [wincache\_ucache\_clear()](function.wincache-ucache-clear) - Deletes entire content of the user cache * [wincache\_ucache\_exists()](function.wincache-ucache-exists) - Checks if a variable exists in the user cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [\_\_sleep()](language.oop5.magic#object.sleep) php ini_set ini\_set ======== (PHP 4, PHP 5, PHP 7, PHP 8) ini\_set — Sets the value of a configuration option ### Description ``` ini_set(string $option, string|int|float|bool|null $value): string|false ``` Sets the value of the given configuration option. The configuration option will keep this new value during the script's execution, and will be restored at the script's ending. ### Parameters `option` Not all the available options can be changed using **ini\_set()**. There is a list of all available options in the [appendix](https://www.php.net/manual/en/ini.list.php). `value` The new value for the option. ### Return Values Returns the old value on success, **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | `value` now accepts any scalar type (including **`null`**). Previously, only string values were accepted. | ### Examples **Example #1 Setting an ini option** ``` <?php echo ini_get('display_errors'); if (!ini_get('display_errors')) {     ini_set('display_errors', '1'); } echo ini_get('display_errors'); ?> ``` ### See Also * [get\_cfg\_var()](function.get-cfg-var) - Gets the value of a PHP configuration option * [ini\_get()](function.ini-get) - Gets the value of a configuration option * [ini\_get\_all()](function.ini-get-all) - Gets all configuration options * [ini\_restore()](function.ini-restore) - Restores the value of a configuration option * [How to change configuration settings](https://www.php.net/manual/en/configuration.changes.php) php ReflectionType::__toString ReflectionType::\_\_toString ============================ (PHP 7, PHP 8) ReflectionType::\_\_toString — To string **Warning**This function has been *DEPRECATED* as of PHP 7.1.0. Relying on this function is highly discouraged. ### Description ``` public ReflectionType::__toString(): string ``` Gets the parameter type name. ### Parameters This function has no parameters. ### Return Values Returns the type of the parameter. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | **ReflectionType::\_\_toString()** has been deprecated. | ### Examples **Example #1 **ReflectionType::\_\_toString()** example** ``` <?php function someFunction(string $param) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParam = $reflectionFunc->getParameters()[0]; echo $reflectionParam->getType(); ``` The above example will output something similar to: ``` string ``` ### See Also * [ReflectionNamedType::getName()](reflectionnamedtype.getname) - Get the name of the type as a string * [ReflectionNamedType::isBuiltin()](reflectionnamedtype.isbuiltin) - Checks if it is a built-in type * [ReflectionType::allowsNull()](reflectiontype.allowsnull) - Checks if null is allowed * [ReflectionUnionType::getTypes()](reflectionuniontype.gettypes) - Returns the types included in the union type * [ReflectionParameter::getType()](reflectionparameter.gettype) - Gets a parameter's type php get_defined_constants get\_defined\_constants ======================= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) get\_defined\_constants — Returns an associative array with the names of all the constants and their values ### Description ``` get_defined_constants(bool $categorize = false): array ``` Returns the names and values of all the constants currently defined. This includes those created by extensions as well as those created with the [define()](function.define) function. ### Parameters `categorize` Causing this function to return a multi-dimensional array with categories in the keys of the first dimension and constants and their values in the second dimension. ``` <?php define("MY_CONSTANT", 1); print_r(get_defined_constants(true)); ?> ``` The above example will output something similar to: ``` Array ( [Core] => Array ( [E_ERROR] => 1 [E_WARNING] => 2 [E_PARSE] => 4 [E_NOTICE] => 8 [E_CORE_ERROR] => 16 [E_CORE_WARNING] => 32 [E_COMPILE_ERROR] => 64 [E_COMPILE_WARNING] => 128 [E_USER_ERROR] => 256 [E_USER_WARNING] => 512 [E_USER_NOTICE] => 1024 [E_ALL] => 2047 [TRUE] => 1 ) [pcre] => Array ( [PREG_PATTERN_ORDER] => 1 [PREG_SET_ORDER] => 2 [PREG_OFFSET_CAPTURE] => 256 [PREG_SPLIT_NO_EMPTY] => 1 [PREG_SPLIT_DELIM_CAPTURE] => 2 [PREG_SPLIT_OFFSET_CAPTURE] => 4 [PREG_GREP_INVERT] => 1 ) [user] => Array ( [MY_CONSTANT] => 1 ) ) ``` ### Return Values Returns an array of constant name => constant value array, optionally groupped by extension name registering the constant. ### Examples **Example #1 **get\_defined\_constants()** Example** ``` <?php print_r(get_defined_constants()); ?> ``` The above example will output something similar to: ``` Array ( [E_ERROR] => 1 [E_WARNING] => 2 [E_PARSE] => 4 [E_NOTICE] => 8 [E_CORE_ERROR] => 16 [E_CORE_WARNING] => 32 [E_COMPILE_ERROR] => 64 [E_COMPILE_WARNING] => 128 [E_USER_ERROR] => 256 [E_USER_WARNING] => 512 [E_USER_NOTICE] => 1024 [E_ALL] => 2047 [TRUE] => 1 ) ``` ### See Also * [defined()](function.defined) - Checks whether a given named constant exists * [constant()](function.constant) - Returns the value of a constant * [get\_loaded\_extensions()](function.get-loaded-extensions) - Returns an array with the names of all modules compiled and loaded * [get\_defined\_functions()](function.get-defined-functions) - Returns an array of all defined functions * [get\_defined\_vars()](function.get-defined-vars) - Returns an array of all defined variables php ibase_errmsg ibase\_errmsg ============= (PHP 5, PHP 7 < 7.4.0) ibase\_errmsg — Return error messages ### Description ``` ibase_errmsg(): string ``` Returns the error message that resulted from the most recent InterBase function call. ### Parameters This function has no parameters. ### Return Values Returns the error message as a string, or **`false`** if no error occurred. ### See Also * [ibase\_errcode()](function.ibase-errcode) - Return an error code php imagecolorsforindex imagecolorsforindex =================== (PHP 4, PHP 5, PHP 7, PHP 8) imagecolorsforindex — Get the colors for an index ### Description ``` imagecolorsforindex(GdImage $image, int $color): array ``` Gets the color for a specified index. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `color` The color index. ### Return Values Returns an associative array with red, green, blue and alpha keys that contain the appropriate values for the specified color index. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | | 8.0.0 | **imagecolorsforindex()** now throws a [ValueError](class.valueerror) exception if `color` is out of range; previously, **`false`** was returned instead. | ### Examples **Example #1 **imagecolorsforindex()** example** ``` <?php // open an image $im = imagecreatefrompng('nexen.png'); // get a color $start_x = 40; $start_y = 50; $color_index = imagecolorat($im, $start_x, $start_y); // make it human readable $color_tran = imagecolorsforindex($im, $color_index); // what is it ? print_r($color_tran); ?> ``` The above example will output something similar to: ``` Array ( [red] => 226 [green] => 222 [blue] => 252 [alpha] => 0 ) ``` ### See Also * [imagecolorat()](function.imagecolorat) - Get the index of the color of a pixel * [imagecolorexact()](function.imagecolorexact) - Get the index of the specified color
programming_docs
php ImagickDraw::composite ImagickDraw::composite ====================== (PECL imagick 2, PECL imagick 3) ImagickDraw::composite — Composites an image onto the current image ### Description ``` public ImagickDraw::composite( int $compose, float $x, float $y, float $width, float $height, Imagick $compositeWand ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Composites an image onto the current image, using the specified composition operator, specified position, and at the specified size. ### Parameters `compose` composition operator. One of the [Composite Operator](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.compositeop) constant (`imagick::COMPOSITE_*`). `x` x coordinate of the top left corner. `y` y coordinate of the top left corner. `width` width of the composition image. `height` height of the composition image. `compositeWand` the [Imagick](class.imagick) object where composition image is taken from. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **ImagickDraw::composite()** example** ``` <?php function composite($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setFillOpacity(1);     $draw->setStrokeWidth(2);     $draw->setFontSize(72);     $draw->setStrokeOpacity(1);     $draw->setStrokeColor($strokeColor);     $draw->setStrokeWidth(2);     $draw->setFont("../fonts/CANDY.TTF");     $draw->setFontSize(140);     $draw->rectangle(0, 0, 1000, 300);     $draw->setFillColor('white');     $draw->setfillopacity(1);     $draw->annotation(50, 180, "Lorem Ipsum!");     //Create an image object which the draw commands can be rendered into     $imagick = new \Imagick();     $imagick->newImage(1000, 302, $backgroundColor);     $imagick->setImageFormat("png");     //Render the draw commands in the ImagickDraw object      //into the image.     $imagick->drawImage($draw);     //Send the image to the browser     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php Yac::flush Yac::flush ========== (PECL yac >= 1.0.0) Yac::flush — Flush the cache ### Description ``` public Yac::flush(): bool ``` Remove all cached values ### Parameters This function has no parameters. ### Return Values bool, always true php gregoriantojd gregoriantojd ============= (PHP 4, PHP 5, PHP 7, PHP 8) gregoriantojd — Converts a Gregorian date to Julian Day Count ### Description ``` gregoriantojd(int $month, int $day, int $year): int ``` The valid range for the Gregorian calendar is from November 25, 4714 B.C. to at least December 31, 9999 A.D. Although this function can handle dates all the way back to 4714 B.C., such use may not be meaningful. The Gregorian calendar was not instituted until October 15, 1582 (or October 5, 1582 in the Julian calendar). Some countries did not accept it until much later. For example, Britain converted in 1752, The USSR in 1918 and Greece in 1923. Most European countries used the Julian calendar prior to the Gregorian. ### Parameters `month` The month as a number from 1 (for January) to 12 (for December) `day` The day as a number from 1 to 31. If the month has less days then given, overflow occurs; see the example below. `year` The year as a number between -4714 and 9999. Negative numbers mean years B.C., positive numbers mean years A.D. Note that there is no year `0`; December 31, 1 B.C. is immediately followed by January 1, 1 A.D. ### Return Values The julian day for the given gregorian date as an integer. Dates outside the valid range return `0`. ### Examples **Example #1 Calendar functions** ``` <?php $jd = gregoriantojd(10, 11, 1970); echo "$jd\n"; $gregorian = jdtogregorian($jd); echo "$gregorian\n"; ?> ``` The above example will output: ``` 2440871 10/11/1970 ``` **Example #2 Overflow behavior** ``` <?php echo gregoriantojd(2, 31, 2018), PHP_EOL,      gregoriantojd(3,  3, 2018), PHP_EOL; ?> ``` The above example will output: ``` 2458181 2458181 ``` ### See Also * [jdtogregorian()](function.jdtogregorian) - Converts Julian Day Count to Gregorian date * [cal\_to\_jd()](function.cal-to-jd) - Converts from a supported calendar to Julian Day Count php count_chars count\_chars ============ (PHP 4, PHP 5, PHP 7, PHP 8) count\_chars — Return information about characters used in a string ### Description ``` count_chars(string $string, int $mode = 0): array|string ``` Counts the number of occurrences of every byte-value (0..255) in `string` and returns it in various ways. ### Parameters `string` The examined string. `mode` See return values. ### Return Values Depending on `mode` **count\_chars()** returns one of the following: * 0 - an array with the byte-value as key and the frequency of every byte as value. * 1 - same as 0 but only byte-values with a frequency greater than zero are listed. * 2 - same as 0 but only byte-values with a frequency equal to zero are listed. * 3 - a string containing all unique characters is returned. * 4 - a string containing all not used characters is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Prior to this version, the function returned **`false`** on failure. | ### Examples **Example #1 **count\_chars()** example** ``` <?php $data = "Two Ts and one F."; foreach (count_chars($data, 1) as $i => $val) {    echo "There were $val instance(s) of \"" , chr($i) , "\" in the string.\n"; } ?> ``` The above example will output: ``` There were 4 instance(s) of " " in the string. There were 1 instance(s) of "." in the string. There were 1 instance(s) of "F" in the string. There were 2 instance(s) of "T" in the string. There were 1 instance(s) of "a" in the string. There were 1 instance(s) of "d" in the string. There were 1 instance(s) of "e" in the string. There were 2 instance(s) of "n" in the string. There were 2 instance(s) of "o" in the string. There were 1 instance(s) of "s" in the string. There were 1 instance(s) of "w" in the string. ``` ### See Also * [strpos()](function.strpos) - Find the position of the first occurrence of a substring in a string * [substr\_count()](function.substr-count) - Count the number of substring occurrences php ImagickDraw::annotation ImagickDraw::annotation ======================= (PECL imagick 2, PECL imagick 3) ImagickDraw::annotation — Draws text on the image ### Description ``` public ImagickDraw::annotation(float $x, float $y, string $text): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws text on the image. ### Parameters `x` The x coordinate where text is drawn `y` The y coordinate where text is drawn `text` The text to draw on the image ### Return Values No value is returned. php clearstatcache clearstatcache ============== (PHP 4, PHP 5, PHP 7, PHP 8) clearstatcache — Clears file status cache ### Description ``` clearstatcache(bool $clear_realpath_cache = false, string $filename = ""): void ``` When you use [stat()](function.stat), [lstat()](function.lstat), or any of the other functions listed in the affected functions list (below), PHP caches the information those functions return in order to provide faster performance. However, in certain cases, you may want to clear the cached information. For instance, if the same file is being checked multiple times within a single script, and that file is in danger of being removed or changed during that script's operation, you may elect to clear the status cache. In these cases, you can use the **clearstatcache()** function to clear the information that PHP caches about a file. You should also note that PHP doesn't cache information about non-existent files. So, if you call [file\_exists()](function.file-exists) on a file that doesn't exist, it will return **`false`** until you create the file. If you create the file, it will return **`true`** even if you then delete the file. However [unlink()](function.unlink) clears the cache automatically. > > **Note**: > > > This function caches information about specific filenames, so you only need to call **clearstatcache()** if you are performing multiple operations on the same filename and require the information about that particular file to not be cached. > > Affected functions include [stat()](function.stat), [lstat()](function.lstat), [file\_exists()](function.file-exists), [is\_writable()](function.is-writable), [is\_readable()](function.is-readable), [is\_executable()](function.is-executable), [is\_file()](function.is-file), [is\_dir()](function.is-dir), [is\_link()](function.is-link), [filectime()](function.filectime), [fileatime()](function.fileatime), [filemtime()](function.filemtime), [fileinode()](function.fileinode), [filegroup()](function.filegroup), [fileowner()](function.fileowner), [filesize()](function.filesize), [filetype()](function.filetype), and [fileperms()](function.fileperms). ### Parameters `clear_realpath_cache` Whether to *also* clear the realpath cache. `filename` Clear the realpath cache for a specific filename only; only used if `clear_realpath_cache` is **`true`**. ### Return Values No value is returned. ### Examples **Example #1 **clearstatcache()** example** ``` <?php $file = 'output_log.txt'; function get_owner($file) {     $stat = stat($file);     $user = posix_getpwuid($stat['uid']);     return $user['name']; } $format = "UID @ %s: %s\n"; printf($format, date('r'), get_owner($file)); chown($file, 'ross'); printf($format, date('r'), get_owner($file)); clearstatcache(); printf($format, date('r'), get_owner($file)); ?> ``` The above example will output something similar to: ``` UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: root UID @ Sun, 12 Oct 2008 20:48:28 +0100: ross ``` php SolrQuery::getHighlightMaxAnalyzedChars SolrQuery::getHighlightMaxAnalyzedChars ======================================= (PECL solr >= 0.9.2) SolrQuery::getHighlightMaxAnalyzedChars — Returns the maximum number of characters into a document to look for suitable snippets ### Description ``` public SolrQuery::getHighlightMaxAnalyzedChars(): int ``` Returns the maximum number of characters into a document to look for suitable snippets ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php GearmanClient::do GearmanClient::do ================= (PECL gearman >= 0.5.0) GearmanClient::do — Run a single task and return a result [deprecated] ### Description ``` public GearmanClient::do(string $function_name, string $workload, string $unique = ?): string ``` The **GearmanClient::do()** method is deprecated as of pecl/gearman 1.0.0. Use [GearmanClient::doNormal()](gearmanclient.donormal). ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `unique` A unique ID used to identify a particular task ### Return Values A string representing the results of running a task. ### Examples **Example #1 Simple job submission with immediate return** ``` <?php # Client code echo "Starting\n"; # Create our client object. $gmclient= new GearmanClient(); # Add default server (localhost). $gmclient->addServer(); echo "Sending job\n"; $result = $gmclient->doNormal("reverse", "Hello!"); echo "Success: $result\n"; ?> ``` ``` <?php echo "Starting\n"; # Create our worker object. $gmworker= new GearmanWorker(); # Add default server (localhost). $gmworker->addServer(); # Register function "reverse" with the server. Change the worker function to # "reverse_fn_fast" for a faster worker with no output. $gmworker->addFunction("reverse", "reverse_fn"); print "Waiting for job...\n"; while($gmworker->work()) {   if ($gmworker->returnCode() != GEARMAN_SUCCESS)   {     echo "return_code: " . $gmworker->returnCode() . "\n";     break;   } } function reverse_fn($job) {   return strrev($job->workload()); } ?> ``` The above example will output something similar to: ``` Starting Sending job Success: !olleH ``` **Example #2 Submitting a job and retrieving incremental status** A job is submitted and the script loops to retrieve status information. The worker has an artificial delay which results in a long running job and sends status and data as processing occurs. Each subsequent call to **GearmanClient::do()** produces status information on the running job. ``` <?php # Client code # Create our client object. $gmclient= new GearmanClient(); # Add default server (localhost). $gmclient->addServer(); echo "Sending job\n"; # Send reverse job do {   $result = $gmclient->doNormal("reverse", "Hello!");   # Check for various return packets and errors.   switch($gmclient->returnCode())   {     case GEARMAN_WORK_DATA:       echo "Data: $result\n";       break;     case GEARMAN_WORK_STATUS:       list($numerator, $denominator)= $gmclient->doStatus();       echo "Status: $numerator/$denominator complete\n";       break;     case GEARMAN_WORK_FAIL:       echo "Failed\n";       exit;     case GEARMAN_SUCCESS:       break;     default:       echo "RET: " . $gmclient->returnCode() . "\n";       echo "Error: " . $gmclient->error() . "\n";       echo "Errno: " . $gmclient->getErrno() . "\n";       exit;   } } while($gmclient->returnCode() != GEARMAN_SUCCESS); echo "Success: $result\n"; ?> ``` ``` <?php # Worker code echo "Starting\n"; # Create our worker object. $gmworker= new GearmanWorker(); # Add default server (localhost). $gmworker->addServer(); # Register function "reverse" with the server. $gmworker->addFunction("reverse", "reverse_fn"); print "Waiting for job...\n"; while($gmworker->work()) {   if ($gmworker->returnCode() != GEARMAN_SUCCESS)   {     echo "return_code: " . $gmworker->returnCode() . "\n";     break;   } } function reverse_fn($job) {   echo "Received job: " . $job->handle() . "\n";   $workload = $job->workload();   $workload_size = $job->workloadSize();   echo "Workload: $workload ($workload_size)\n";   # This status loop is not needed, just showing how it works   for ($x= 0; $x < $workload_size; $x++)   {     echo "Sending status: " + $x + 1 . "/$workload_size complete\n";     $job->sendStatus($x+1, $workload_size);     $job->sendData(substr($workload, $x, 1));     sleep(1);   }   $result= strrev($workload);   echo "Result: $result\n";   # Return what we want to send back to the client.   return $result; } ?> ``` The above example will output something similar to: Worker output: ``` Starting Waiting for job... Received job: H:foo.local:106 Workload: Hello! (6) 1/6 complete 2/6 complete 3/6 complete 4/6 complete 5/6 complete 6/6 complete Result: !olleH ``` Client output: ``` Starting Sending job Status: 1/6 complete Data: H Status: 2/6 complete Data: e Status: 3/6 complete Data: l Status: 4/6 complete Data: l Status: 5/6 complete Data: o Status: 6/6 complete Data: ! Success: !olleH ``` ### See Also * [GearmanClient::doHigh()](gearmanclient.dohigh) - Run a single high priority task * [GearmanClient::doLow()](gearmanclient.dolow) - Run a single low priority task * [GearmanClient::doBackground()](gearmanclient.dobackground) - Run a task in the background * [GearmanClient::doHighBackground()](gearmanclient.dohighbackground) - Run a high priority task in the background * [GearmanClient::doLowBackground()](gearmanclient.dolowbackground) - Run a low priority task in the background php SolrDocument::__clone SolrDocument::\_\_clone ======================= (PECL solr >= 0.9.2) SolrDocument::\_\_clone — Creates a copy of a SolrDocument object ### Description ``` public SolrDocument::__clone(): void ``` Creates a copy of a SolrDocument object. Not to be called directly. ### Parameters This function has no parameters. ### Return Values None. php Memcached::getDelayed Memcached::getDelayed ===================== (PECL memcached >= 0.1.0) Memcached::getDelayed — Request multiple items ### Description ``` public Memcached::getDelayed(array $keys, bool $with_cas = ?, callable $value_cb = ?): bool ``` **Memcached::getDelayed()** issues a request to memcache for multiple items the keys of which are specified in the `keys` array. The method does not wait for response and returns right away. When you are ready to collect the items, call either [Memcached::fetch()](memcached.fetch) or [Memcached::fetchAll()](memcached.fetchall). If `with_cas` is true, the CAS token values will also be requested. Instead of fetching the results explicitly, you can specify a [result callback](https://www.php.net/manual/en/memcached.callbacks.php) via `value_cb` parameter. ### Parameters `keys` Array of keys to request. `with_cas` Whether to request CAS token values also. `value_cb` The result callback or **`null`**. ### Return Values Returns **`true`** on success or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary. ### Examples **Example #1 **Memcached::getDelayed()** example** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); $m->set('int', 99); $m->set('string', 'a simple string'); $m->set('array', array(11, 12)); $m->getDelayed(array('int', 'array'), true); var_dump($m->fetchAll()); ?> ``` The above example will output: ``` array(2) { [0]=> array(3) { ["key"]=> string(3) "int" ["value"]=> int(99) ["cas"]=> float(2363) } [1]=> array(3) { ["key"]=> string(5) "array" ["value"]=> array(2) { [0]=> int(11) [1]=> int(12) } ["cas"]=> float(2365) } } ``` ### See Also * [Memcached::getDelayedByKey()](memcached.getdelayedbykey) - Request multiple items from a specific server * [Memcached::fetch()](memcached.fetch) - Fetch the next result * [Memcached::fetchAll()](memcached.fetchall) - Fetch all the remaining results php The AddressInfo class The AddressInfo class ===================== Introduction ------------ (PHP 8) A fully opaque class which replaces `AddressInfo` resources as of PHP 8.0.0. Class synopsis -------------- final class **AddressInfo** { } php xmlrpc_set_type xmlrpc\_set\_type ================= (PHP 4 >= 4.1.0, PHP 5, PHP 7) xmlrpc\_set\_type — Sets xmlrpc type, base64 or datetime, for a PHP string value ### Description ``` xmlrpc_set_type(string &$value, string $type): bool ``` Sets xmlrpc type, base64 or datetime, for a PHP string value. **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. ### Parameters `value` Value to set the type `type` 'base64' or 'datetime' ### Return Values Returns **`true`** on success or **`false`** on failure. If successful, `value` is converted to an object. ### Errors/Exceptions Issues E\_WARNING with type unsupported by XMLRPC. ### Examples **Example #1 A **xmlrpc\_set\_type()** example** ``` <?php $params = date("Ymd\TH:i:s", time()); xmlrpc_set_type($params, 'datetime'); echo xmlrpc_encode($params); ?> ``` The above example will output something similar to: ``` <?xml version="1.0" encoding="utf-8"?> <params> <param> <value> <dateTime.iso8601>20090322T23:43:03</dateTime.iso8601> </value> </param> </params> ```
programming_docs
php sqlsrv_query sqlsrv\_query ============= (No version information available, might only be in Git) sqlsrv\_query — Prepares and executes a query ### Description ``` sqlsrv_query( resource $conn, string $sql, array $params = ?, array $options = ? ): mixed ``` Prepares and executes a query. ### Parameters `conn` A connection resource returned by [sqlsrv\_connect()](function.sqlsrv-connect). `sql` The string that defines the query to be prepared and executed. `params` An array specifying parameter information when executing a parameterized query. Array elements can be any of the following: * A literal value * A PHP variable * An array with this structure: array($value [, $direction [, $phpType [, $sqlType]]]) The following table describes the elements in the array structure above: **Array structure**| Element | Description | | --- | --- | | $value | A literal value, a PHP variable, or a PHP by-reference variable. | | $direction (optional) | One of the following SQLSRV constants used to indicate the parameter direction: SQLSRV\_PARAM\_IN, SQLSRV\_PARAM\_OUT, SQLSRV\_PARAM\_INOUT. The default value is SQLSRV\_PARAM\_IN. | | $phpType (optional) | A SQLSRV\_PHPTYPE\_\* constant that specifies PHP data type of the returned value. | | $sqlType (optional) | A SQLSRV\_SQLTYPE\_\* constant that specifies the SQL Server data type of the input value. | `options` An array specifying query property options. The supported keys are described in the following table: **Query Options**| Key | Values | Description | | --- | --- | --- | | QueryTimeout | A positive integer value. | Sets the query timeout in seconds. By default, the driver will wait indefinitely for results. | | SendStreamParamsAtExec | **`true`** or **`false`** (the default is **`true`**) | Configures the driver to send all stream data at execution (**`true`**), or to send stream data in chunks (**`false`**). By default, the value is set to **`true`**. For more information, see [sqlsrv\_send\_stream\_data()](function.sqlsrv-send-stream-data). | | Scrollable | SQLSRV\_CURSOR\_FORWARD, SQLSRV\_CURSOR\_STATIC, SQLSRV\_CURSOR\_DYNAMIC, or SQLSRV\_CURSOR\_KEYSET | See [» Specifying a Cursor Type and Selecting Rows](http://msdn.microsoft.com/en-us/library/ee376927.aspx) in the Microsoft SQLSRV documentation. | ### Return Values Returns a statement resource on success and **`false`** if an error occurred. ### Examples **Example #1 **sqlsrv\_query()** example** ``` <?php $serverName = "serverName\sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password" ); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } $sql = "INSERT INTO Table_1 (id, data) VALUES (?, ?)"; $params = array(1, "some data"); $stmt = sqlsrv_query( $conn, $sql, $params); if( $stmt === false ) {      die( print_r( sqlsrv_errors(), true)); } ?> ``` ### Notes For statements that you plan to execute only once, use **sqlsrv\_query()**. If you intend to re-execute a statement with different parameter values, use the combination of [sqlsrv\_prepare()](function.sqlsrv-prepare) and [sqlsrv\_execute()](function.sqlsrv-execute). ### See Also * [sqlsrv\_prepare()](function.sqlsrv-prepare) - Prepares a query for execution * [sqlsrv\_execute()](function.sqlsrv-execute) - Executes a statement prepared with sqlsrv\_prepare php mb_ereg_search_regs mb\_ereg\_search\_regs ====================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) mb\_ereg\_search\_regs — Returns the matched part of a multibyte regular expression ### Description ``` mb_ereg_search_regs(?string $pattern = null, ?string $options = null): array|false ``` Returns the matched part of a multibyte regular expression. ### Parameters `pattern` The search pattern. `options` The search option. See [mb\_regex\_set\_options()](function.mb-regex-set-options) for explanation. ### Return Values **mb\_ereg\_search\_regs()** executes the multibyte regular expression match, and if there are some matched part, it returns an array including substring of matched part as first element, the first grouped part with brackets as second element, the second grouped part as third element, and so on. It returns **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `pattern` and `options` are nullable now. | ### Notes > > **Note**: > > > The internal encoding or the character encoding specified by [mb\_regex\_encoding()](function.mb-regex-encoding) will be used as the character encoding for this function. > > > ### See Also * [mb\_regex\_encoding()](function.mb-regex-encoding) - Set/Get character encoding for multibyte regex * [mb\_ereg\_search\_init()](function.mb-ereg-search-init) - Setup string and regular expression for a multibyte regular expression match php None Bitwise Operators ----------------- Bitwise operators allow evaluation and manipulation of specific bits within an integer. **Bitwise Operators**| Example | Name | Result | | --- | --- | --- | | **`$a & $b`** | And | Bits that are set in both $a and $b are set. | | **`$a | $b`** | Or (inclusive or) | Bits that are set in either $a or $b are set. | | **`$a ^ $b`** | Xor (exclusive or) | Bits that are set in $a or $b but not both are set. | | **`~ $a`** | Not | Bits that are set in $a are not set, and vice versa. | | **`$a << $b`** | Shift left | Shift the bits of $a $b steps to the left (each step means "multiply by two") | | **`$a >> $b`** | Shift right | Shift the bits of $a $b steps to the right (each step means "divide by two") | Bit shifting in PHP is arithmetic. Bits shifted off either end are discarded. Left shifts have zeros shifted in on the right while the sign bit is shifted out on the left, meaning the sign of an operand is not preserved. Right shifts have copies of the sign bit shifted in on the left, meaning the sign of an operand is preserved. Use parentheses to ensure the desired [precedence](language.operators.precedence). For example, `$a & $b == true` evaluates the equivalency then the bitwise and; while `($a & $b) == true` evaluates the bitwise and then the equivalency. If both operands for the `&`, `|` and `^` operators are strings, then the operation will be performed on the ASCII values of the characters that make up the strings and the result will be a string. In all other cases, both operands will be [converted to integers](language.types.integer#language.types.integer.casting) and the result will be an integer. If the operand for the `~` operator is a string, the operation will be performed on the ASCII values of the characters that make up the string and the result will be a string, otherwise the operand and the result will be treated as integers. Both operands and the result for the `<<` and `>>` operators are always treated as integers. ``` PHP's error_reporting ini setting uses bitwise values, providing a real-world demonstration of turning bits off. To show all errors, except for notices, the php.ini file instructions say to use: **`E_ALL & ~E_NOTICE`** ``` ``` This works by starting with E_ALL: 00000000000000000111011111111111 Then taking the value of E_NOTICE... 00000000000000000000000000001000 ... and inverting it via ~: 11111111111111111111111111110111 Finally, it uses AND (&) to find the bits turned on in both values: 00000000000000000111011111110111 ``` ``` Another way to accomplish that is using XOR (^) to find bits that are on in only one value or the other: **`E_ALL ^ E_NOTICE`** ``` ``` error_reporting can also be used to demonstrate turning bits on. The way to show just errors and recoverable errors is: **`E_ERROR | E_RECOVERABLE_ERROR`** ``` ``` This process combines E_ERROR 00000000000000000000000000000001 and 00000000000000000001000000000000 using the OR (|) operator to get the bits turned on in either value: 00000000000000000001000000000001 ``` **Example #1 Bitwise AND, OR and XOR operations on integers** ``` <?php /*  * Ignore the top section,  * it is just formatting to make output clearer.  */ $format = '(%1$2d = %1$04b) = (%2$2d = %2$04b)'         . ' %3$s (%4$2d = %4$04b)' . "\n"; echo <<<EOH  ---------     ---------  -- ---------  result        value      op test  ---------     ---------  -- --------- EOH; /*  * Here are the examples.  */ $values = array(0, 1, 2, 4, 8); $test = 1 + 4; echo "\n Bitwise AND \n"; foreach ($values as $value) {     $result = $value & $test;     printf($format, $result, $value, '&', $test); } echo "\n Bitwise Inclusive OR \n"; foreach ($values as $value) {     $result = $value | $test;     printf($format, $result, $value, '|', $test); } echo "\n Bitwise Exclusive OR (XOR) \n"; foreach ($values as $value) {     $result = $value ^ $test;     printf($format, $result, $value, '^', $test); } ?> ``` The above example will output: ``` --------- --------- -- --------- result value op test --------- --------- -- --------- Bitwise AND ( 0 = 0000) = ( 0 = 0000) & ( 5 = 0101) ( 1 = 0001) = ( 1 = 0001) & ( 5 = 0101) ( 0 = 0000) = ( 2 = 0010) & ( 5 = 0101) ( 4 = 0100) = ( 4 = 0100) & ( 5 = 0101) ( 0 = 0000) = ( 8 = 1000) & ( 5 = 0101) Bitwise Inclusive OR ( 5 = 0101) = ( 0 = 0000) | ( 5 = 0101) ( 5 = 0101) = ( 1 = 0001) | ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) | ( 5 = 0101) ( 5 = 0101) = ( 4 = 0100) | ( 5 = 0101) (13 = 1101) = ( 8 = 1000) | ( 5 = 0101) Bitwise Exclusive OR (XOR) ( 5 = 0101) = ( 0 = 0000) ^ ( 5 = 0101) ( 4 = 0100) = ( 1 = 0001) ^ ( 5 = 0101) ( 7 = 0111) = ( 2 = 0010) ^ ( 5 = 0101) ( 1 = 0001) = ( 4 = 0100) ^ ( 5 = 0101) (13 = 1101) = ( 8 = 1000) ^ ( 5 = 0101) ``` **Example #2 Bitwise XOR operations on strings** ``` <?php echo 12 ^ 9; // Outputs '5' echo "12" ^ "9"; // Outputs the Backspace character (ascii 8)                  // ('1' (ascii 49)) ^ ('9' (ascii 57)) = #8 echo "hallo" ^ "hello"; // Outputs the ascii values #0 #4 #0 #0 #0                         // 'a' ^ 'e' = #4 echo 2 ^ "3"; // Outputs 1               // 2 ^ ((int)"3") == 1 echo "2" ^ 3; // Outputs 1               // ((int)"2") ^ 3 == 1 ?> ``` **Example #3 Bit shifting on integers** ``` <?php /*  * Here are the examples.  */ echo "\n--- BIT SHIFT RIGHT ON POSITIVE INTEGERS ---\n"; $val = 4; $places = 1; $res = $val >> $places; p($res, $val, '>>', $places, 'copy of sign bit shifted into left side'); $val = 4; $places = 2; $res = $val >> $places; p($res, $val, '>>', $places); $val = 4; $places = 3; $res = $val >> $places; p($res, $val, '>>', $places, 'bits shift out right side'); $val = 4; $places = 4; $res = $val >> $places; p($res, $val, '>>', $places, 'same result as above; can not shift beyond 0'); echo "\n--- BIT SHIFT RIGHT ON NEGATIVE INTEGERS ---\n"; $val = -4; $places = 1; $res = $val >> $places; p($res, $val, '>>', $places, 'copy of sign bit shifted into left side'); $val = -4; $places = 2; $res = $val >> $places; p($res, $val, '>>', $places, 'bits shift out right side'); $val = -4; $places = 3; $res = $val >> $places; p($res, $val, '>>', $places, 'same result as above; can not shift beyond -1'); echo "\n--- BIT SHIFT LEFT ON POSITIVE INTEGERS ---\n"; $val = 4; $places = 1; $res = $val << $places; p($res, $val, '<<', $places, 'zeros fill in right side'); $val = 4; $places = (PHP_INT_SIZE * 8) - 4; $res = $val << $places; p($res, $val, '<<', $places); $val = 4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, '<<', $places, 'sign bits get shifted out'); $val = 4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, '<<', $places, 'bits shift out left side'); echo "\n--- BIT SHIFT LEFT ON NEGATIVE INTEGERS ---\n"; $val = -4; $places = 1; $res = $val << $places; p($res, $val, '<<', $places, 'zeros fill in right side'); $val = -4; $places = (PHP_INT_SIZE * 8) - 3; $res = $val << $places; p($res, $val, '<<', $places); $val = -4; $places = (PHP_INT_SIZE * 8) - 2; $res = $val << $places; p($res, $val, '<<', $places, 'bits shift out left side, including sign bit'); /*  * Ignore this bottom section,  * it is just formatting to make output clearer.  */ function p($res, $val, $op, $places, $note = '') {     $format = '%0' . (PHP_INT_SIZE * 8) . "b\n";     printf("Expression: %d = %d %s %d\n", $res, $val, $op, $places);     echo " Decimal:\n";     printf("  val=%d\n", $val);     printf("  res=%d\n", $res);     echo " Binary:\n";     printf('  val=' . $format, $val);     printf('  res=' . $format, $res);     if ($note) {         echo " NOTE: $note\n";     }     echo "\n"; } ?> ``` Output of the above example on 32 bit machines: ``` --- BIT SHIFT RIGHT ON POSITIVE INTEGERS --- Expression: 2 = 4 >> 1 Decimal: val=4 res=2 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000001000 NOTE: zeros fill in right side Expression: 1073741824 = 4 << 28 Decimal: val=4 res=1073741824 Binary: val=00000000000000000000000000000100 res=01000000000000000000000000000000 Expression: -2147483648 = 4 << 29 Decimal: val=4 res=-2147483648 Binary: val=00000000000000000000000000000100 res=10000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 30 Decimal: val=4 res=0 Binary: val=00000000000000000000000000000100 res=00000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=11111111111111111111111111111100 res=11111111111111111111111111111000 NOTE: zeros fill in right side Expression: -2147483648 = -4 << 29 Decimal: val=-4 res=-2147483648 Binary: val=11111111111111111111111111111100 res=10000000000000000000000000000000 Expression: 0 = -4 << 30 Decimal: val=-4 res=0 Binary: val=11111111111111111111111111111100 res=00000000000000000000000000000000 NOTE: bits shift out left side, including sign bit ``` Output of the above example on 64 bit machines: ``` --- BIT SHIFT RIGHT ON POSITIVE INTEGERS --- Expression: 2 = 4 >> 1 Decimal: val=4 res=2 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000010 NOTE: copy of sign bit shifted into left side Expression: 1 = 4 >> 2 Decimal: val=4 res=1 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000001 Expression: 0 = 4 >> 3 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out right side Expression: 0 = 4 >> 4 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: same result as above; can not shift beyond 0 --- BIT SHIFT RIGHT ON NEGATIVE INTEGERS --- Expression: -2 = -4 >> 1 Decimal: val=-4 res=-2 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111110 NOTE: copy of sign bit shifted into left side Expression: -1 = -4 >> 2 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: bits shift out right side Expression: -1 = -4 >> 3 Decimal: val=-4 res=-1 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111111 NOTE: same result as above; can not shift beyond -1 --- BIT SHIFT LEFT ON POSITIVE INTEGERS --- Expression: 8 = 4 << 1 Decimal: val=4 res=8 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000001000 NOTE: zeros fill in right side Expression: 4611686018427387904 = 4 << 60 Decimal: val=4 res=4611686018427387904 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0100000000000000000000000000000000000000000000000000000000000000 Expression: -9223372036854775808 = 4 << 61 Decimal: val=4 res=-9223372036854775808 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=1000000000000000000000000000000000000000000000000000000000000000 NOTE: sign bits get shifted out Expression: 0 = 4 << 62 Decimal: val=4 res=0 Binary: val=0000000000000000000000000000000000000000000000000000000000000100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side --- BIT SHIFT LEFT ON NEGATIVE INTEGERS --- Expression: -8 = -4 << 1 Decimal: val=-4 res=-8 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1111111111111111111111111111111111111111111111111111111111111000 NOTE: zeros fill in right side Expression: -9223372036854775808 = -4 << 61 Decimal: val=-4 res=-9223372036854775808 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=1000000000000000000000000000000000000000000000000000000000000000 Expression: 0 = -4 << 62 Decimal: val=-4 res=0 Binary: val=1111111111111111111111111111111111111111111111111111111111111100 res=0000000000000000000000000000000000000000000000000000000000000000 NOTE: bits shift out left side, including sign bit ``` **Warning** Use functions from the [gmp](https://www.php.net/manual/en/book.gmp.php) extension for bitwise manipulation on numbers beyond `PHP_INT_MAX`. ### See Also * [pack()](function.pack) * [unpack()](function.unpack) * [gmp\_and()](function.gmp-and) * [gmp\_or()](function.gmp-or) * [gmp\_xor()](function.gmp-xor) * [gmp\_testbit()](function.gmp-testbit) * [gmp\_clrbit()](function.gmp-clrbit) php Locale::getDisplayRegion Locale::getDisplayRegion ======================== locale\_get\_display\_region ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::getDisplayRegion -- locale\_get\_display\_region — Returns an appropriately localized display name for region of the input locale ### Description Object-oriented style ``` public static Locale::getDisplayRegion(string $locale, ?string $displayLocale = null): string|false ``` Procedural style ``` locale_get_display_region(string $locale, ?string $displayLocale = null): string|false ``` Returns an appropriately localized display name for region of the input locale. If is **`null`** then the default locale is used. ### Parameters `locale` The locale to return a display region for. `displayLocale` Optional format locale to use to display the region name ### Return Values Display name of the region for the `locale` in the format appropriate for `displayLocale`, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `displayLocale` is nullable now. | ### Examples **Example #1 **locale\_get\_display\_region()** example** ``` <?php echo locale_get_display_region('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo locale_get_display_region('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo locale_get_display_region('sl-Latn-IT-nedis', 'de'); ?> ``` **Example #2 OO example** ``` <?php echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo Locale::getDisplayRegion('sl-Latn-IT-nedis', 'de'); ?> ``` The above example will output: ``` Italy; Italie; Italien ``` ### See Also * [locale\_get\_display\_name()](locale.getdisplayname) - Returns an appropriately localized display name for the input locale * [locale\_get\_display\_language()](locale.getdisplaylanguage) - Returns an appropriately localized display name for language of the inputlocale * [locale\_get\_display\_script()](locale.getdisplayscript) - Returns an appropriately localized display name for script of the input locale * [locale\_get\_display\_variant()](locale.getdisplayvariant) - Returns an appropriately localized display name for variants of the input locale
programming_docs
php get_meta_tags get\_meta\_tags =============== (PHP 4, PHP 5, PHP 7, PHP 8) get\_meta\_tags — Extracts all meta tag content attributes from a file and returns an array ### Description ``` get_meta_tags(string $filename, bool $use_include_path = false): array|false ``` Opens `filename` and parses it line by line for <meta> tags in the file. The parsing stops at `</head>`. ### Parameters `filename` The path to the HTML file, as a string. This can be a local file or an URL. **Example #1 What **get\_meta\_tags()** parses** ``` <meta name="author" content="name"> <meta name="keywords" content="php documentation"> <meta name="DESCRIPTION" content="a php manual"> <meta name="geo.position" content="49.33;-86.59"> </head> <!-- parsing stops here --> ``` `use_include_path` Setting `use_include_path` to **`true`** will result in PHP trying to open the file along the standard include path as per the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path) directive. This is used for local files, not URLs. ### Return Values Returns an array with all the parsed meta tags. The value of the name property becomes the key, the value of the content property becomes the value of the returned array, so you can easily use standard array functions to traverse it or access single values. Special characters in the value of the name property are substituted with '\_', the rest is converted to lower case. If two meta tags have the same name, only the last one is returned. Returns **`false`** on failure. ### Examples **Example #2 What **get\_meta\_tags()** returns** ``` <?php // Assuming the above tags are at www.example.com $tags = get_meta_tags('http://www.example.com/'); // Notice how the keys are all lowercase now, and // how . was replaced by _ in the key. echo $tags['author'];       // name echo $tags['keywords'];     // php documentation echo $tags['description'];  // a php manual echo $tags['geo_position']; // 49.33;-86.59 ?> ``` ### Notes > > **Note**: > > > Only meta tags with name attributes will be parsed. Quotes are not required. > > ### See Also * [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities * [urlencode()](function.urlencode) - URL-encodes string php link link ==== (PHP 4, PHP 5, PHP 7, PHP 8) link — Create a hard link ### Description ``` link(string $target, string $link): bool ``` **link()** creates a hard link. ### Parameters `target` Target of the link. `link` The link name. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions The function fails, and issues **`E_WARNING`**, if `link` already exists, or if `target` does not exist. ### Examples **Example #1 Creating a simple hard link** ``` <?php $target = 'source.ext'; // This is the file that already exists $link = 'newfile.ext'; // This the filename that you want to link it to link($target, $link); ?> ``` ### Notes > **Note**: This function will not work on [remote files](https://www.php.net/manual/en/features.remote-files.php) as the file to be examined must be accessible via the server's filesystem. > > > **Note**: For Windows only: This function requires PHP to run in an elevated mode or with the UAC disabled. > > ### See Also * [symlink()](function.symlink) - Creates a symbolic link * [readlink()](function.readlink) - Returns the target of a symbolic link * [linkinfo()](function.linkinfo) - Gets information about a link * [unlink()](function.unlink) - Deletes a file php xml_get_error_code xml\_get\_error\_code ===================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_get\_error\_code — Get XML parser error code ### Description ``` xml_get_error_code(XMLParser $parser): int ``` Gets the XML parser error code. ### Parameters `parser` A reference to the XML parser to get error code from. ### Return Values This function returns **`false`** if `parser` does not refer to a valid parser, or else it returns one of the error codes listed in the [error codes section](https://www.php.net/manual/en/xml.error-codes.php). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | ### See Also * [xml\_error\_string()](function.xml-error-string) - Get XML parser error string php RecursiveDirectoryIterator::next RecursiveDirectoryIterator::next ================================ (PHP 5, PHP 7, PHP 8) RecursiveDirectoryIterator::next — Move to next entry ### Description ``` public RecursiveDirectoryIterator::next(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php Parle\RParser::left Parle\RParser::left =================== (PECL parle >= 0.7.0) Parle\RParser::left — Declare a token with left-associativity ### Description ``` public Parle\RParser::left(string $tok): void ``` Declare a terminal with left associativity. ### Parameters `tok` Token name. ### Return Values No value is returned. php EvIo::set EvIo::set ========= (PECL ev >= 0.2.0) EvIo::set — Configures the watcher ### Description ``` public EvIo::set( mixed $fd , int $events ): void ``` Configures the EvIo watcher ### Parameters `fd` The same as for [EvIo::\_\_construct()](evio.construct) `events` The same as for [EvIo::\_\_construct()](evio.construct) ### Return Values No value is returned. php RarEntry::getAttr RarEntry::getAttr ================= (PECL rar >= 0.1) RarEntry::getAttr — Get attributes of the entry ### Description ``` public RarEntry::getAttr(): int ``` Returns the OS-dependent attributes of the archive entry. ### Parameters This function has no parameters. ### Return Values Returns the attributes or **`false`** on error. ### Examples **Example #1 **RarEntry::getAttr()** example** ``` <?php $rar_file = rar_open('example.rar') or die("Can't open Rar archive"); $entry = rar_entry_get($rar_file, 'dir/in/the/archive') or die("Can't find such entry"); $host_os = $entry->getHostOs(); $attr = $entry->getAttr(); switch($host_os) {     case RAR_HOST_MSDOS:     case RAR_HOST_OS2:     case RAR_HOST_WIN32:     case RAR_HOST_MACOS:         printf("%c%c%c%c%c%c\n",                 ($attr & 0x08) ? 'V' : '.',                 ($attr & 0x10) ? 'D' : '.',                 ($attr & 0x01) ? 'R' : '.',                 ($attr & 0x02) ? 'H' : '.',                 ($attr & 0x04) ? 'S' : '.',                 ($attr & 0x20) ? 'A' : '.');         break;     case RAR_HOST_UNIX:     case RAR_HOST_BEOS:         switch ($attr & 0xF000)         {             case 0x4000:                 printf("d");                 break;             case 0xA000:                 printf("l");                 break;             default:                 printf("-");                 break;         }         printf("%c%c%c%c%c%c%c%c%c\n",                 ($attr & 0x0100) ? 'r' : '-',                 ($attr & 0x0080) ? 'w' : '-',                 ($attr & 0x0040) ? (($attr & 0x0800) ? 's':'x'):(($attr & 0x0800) ? 'S':'-'),                 ($attr & 0x0020) ? 'r' : '-',                 ($attr & 0x0010) ? 'w' : '-',                 ($attr & 0x0008) ? (($attr & 0x0400) ? 's':'x'):(($attr & 0x0400) ? 'S':'-'),                 ($attr & 0x0004) ? 'r' : '-',                 ($attr & 0x0002) ? 'w' : '-',                 ($attr & 0x0001) ? 'x' : '-');         break; } rar_close($rar_file); ?> ``` ### See Also * [RarEntry::getHostOs()](rarentry.gethostos) - Get entry host OS * The constants in [RarEntry](class.rarentry) php get_cfg_var get\_cfg\_var ============= (PHP 4, PHP 5, PHP 7, PHP 8) get\_cfg\_var — Gets the value of a PHP configuration option ### Description ``` get_cfg_var(string $option): string|array|false ``` Gets the value of a PHP configuration `option`. This function will not return configuration information set when the PHP was compiled, or read from an Apache configuration file. To check whether the system is using a [configuration file](https://www.php.net/manual/en/configuration.file.php), try retrieving the value of the cfg\_file\_path configuration setting. If this is available, a configuration file is being used. ### Parameters `option` The configuration option name. ### Return Values Returns the current value of the PHP configuration variable specified by `option`, or **`false`** if an error occurs. ### See Also * [ini\_get()](function.ini-get) - Gets the value of a configuration option * [ini\_get\_all()](function.ini-get-all) - Gets all configuration options php dba_list dba\_list ========= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) dba\_list — List all open database files ### Description ``` dba_list(): array ``` **dba\_list()** list all open database files. ### Parameters This function has no parameters. ### Return Values An associative array, in the form `resourceid => filename`. php imap_scanmailbox imap\_scanmailbox ================= (PHP 4, PHP 5, PHP 7, PHP 8) imap\_scanmailbox — Alias of [imap\_listscan()](function.imap-listscan) ### Description This function is an alias of: [imap\_listscan()](function.imap-listscan). php posix_access posix\_access ============= (PHP 5 >= 5.1.0, PHP 7, PHP 8) posix\_access — Determine accessibility of a file ### Description ``` posix_access(string $filename, int $flags = 0): bool ``` **posix\_access()** checks the user's permission of a file. ### Parameters `filename` The name of the file to be tested. `flags` A mask consisting of one or more of **`POSIX_F_OK`**, **`POSIX_R_OK`**, **`POSIX_W_OK`** and **`POSIX_X_OK`**. **`POSIX_R_OK`**, **`POSIX_W_OK`** and **`POSIX_X_OK`** request checking whether the file exists and has read, write and execute permissions, respectively. **`POSIX_F_OK`** just requests checking for the existence of the file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **posix\_access()** example** This example will check if the $file is readable and writable, otherwise will print an error message. ``` <?php $file = 'some_file'; if (posix_access($file, POSIX_R_OK | POSIX_W_OK)) {     echo 'The file is readable and writable!'; } else {     $error = posix_get_last_error();     echo "Error $error: " . posix_strerror($error); } ?> ``` ### Notes ### See Also * [posix\_get\_last\_error()](function.posix-get-last-error) - Retrieve the error number set by the last posix function that failed * [posix\_strerror()](function.posix-strerror) - Retrieve the system error message associated with the given errno php intl_get_error_code intl\_get\_error\_code ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) intl\_get\_error\_code — Get the last error code ### Description ``` intl_get_error_code(): int ``` Useful to handle errors occurred in static methods when there's no object to get error code from. ### Parameters This function has no parameters. ### Return Values Error code returned by the last API function call. ### Examples **Example #1 **intl\_get\_error\_code()** example** ``` <?php $coll = collator_create( '<bad_param>' ); if( !$coll ) {     handle_error( intl_get_error_code() ); } ?> ``` ### See Also * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure * [intl\_error\_name()](function.intl-error-name) - Get symbolic name for a given error code * [intl\_get\_error\_message()](function.intl-get-error-message) - Get description of the last error * [collator\_get\_error\_code()](collator.geterrorcode) - Get collator's last error code * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code php pg_lo_export pg\_lo\_export ============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_export — Export a large object to file ### Description ``` pg_lo_export(PgSql\Connection $connection = ?, int $oid, string $pathname): bool ``` **pg\_lo\_export()** takes a large object in a PostgreSQL database and saves its contents to a file on the local filesystem. To use the large object interface, it is necessary to enclose it within a transaction block. > > **Note**: > > > This function used to be called **pg\_loexport()**. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `oid` The OID of the large object in the database. `pathname` The full path and file name of the file in which to write the large object on the client filesystem. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_export()** example** ``` <?php    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $oid = pg_lo_create($database);    $handle = pg_lo_open($database, $oid, "w");    pg_lo_write($handle, "large object data");    pg_lo_close($handle);    pg_lo_export($database, $oid, '/tmp/lob.dat');    pg_query($database, "commit"); ?> ``` ### See Also * [pg\_lo\_import()](function.pg-lo-import) - Import a large object from file php The ZookeeperConfig class The ZookeeperConfig class ========================= Introduction ------------ (PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0) The ZooKeeper Config handling class. Class synopsis -------------- class **ZookeeperConfig** { /\* Methods \*/ ``` public add(string $members, int $version = -1, array &$stat = null): void ``` ``` public get(callable $watcher_cb = null, array &$stat = null): string ``` ``` public remove(string $id_list, int $version = -1, array &$stat = null): void ``` ``` public set(string $members, int $version = -1, array &$stat = null): void ``` } Table of Contents ----------------- * [ZookeeperConfig::add](zookeeperconfig.add) — Add servers to the ensemble * [ZookeeperConfig::get](zookeeperconfig.get) — Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously * [ZookeeperConfig::remove](zookeeperconfig.remove) — Remove servers from the ensemble * [ZookeeperConfig::set](zookeeperconfig.set) — Change ZK cluster ensemble membership and roles of ensemble peers php Imagick::setImageUnits Imagick::setImageUnits ====================== (PECL imagick 2, PECL imagick 3) Imagick::setImageUnits — Sets the image units of resolution ### Description ``` public Imagick::setImageUnits(int $units): bool ``` Sets the image units of resolution. ### Parameters `units` ### Return Values Returns **`true`** on success. php IntlChar::isUAlphabetic IntlChar::isUAlphabetic ======================= (PHP 7, PHP 8) IntlChar::isUAlphabetic — Check if code point has the Alphabetic Unicode property ### Description ``` public static IntlChar::isUAlphabetic(int|string $codepoint): ?bool ``` Check if a code point has the Alphabetic Unicode property. This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_ALPHABETIC)` ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` has the Alphabetic Unicode property, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isUAlphabetic("A")); var_dump(IntlChar::isUAlphabetic("1")); var_dump(IntlChar::isUAlphabetic("\u{2603}")); ?> ``` The above example will output: ``` bool(true) bool(false) bool(false) ``` ### See Also * [IntlChar::isalpha()](intlchar.isalpha) - Check if code point is a letter character * [IntlChar::hasBinaryProperty()](intlchar.hasbinaryproperty) - Check a binary Unicode property for a code point * **`IntlChar::PROPERTY_ALPHABETIC`** php Exception::getTraceAsString Exception::getTraceAsString =========================== (PHP 5, PHP 7, PHP 8) Exception::getTraceAsString — Gets the stack trace as a string ### Description ``` final public Exception::getTraceAsString(): string ``` Returns the Exception stack trace as a string. ### Parameters This function has no parameters. ### Return Values Returns the Exception stack trace as a string. ### Examples **Example #1 **Exception::getTraceAsString()** example** ``` <?php function test() {     throw new Exception; } try {     test(); } catch(Exception $e) {     echo $e->getTraceAsString(); } ?> ``` The above example will output something similar to: ``` #0 /home/bjori/tmp/ex.php(7): test() #1 {main} ``` ### See Also * [Throwable::getTraceAsString()](throwable.gettraceasstring) - Gets the stack trace as a string php pcntl_wexitstatus pcntl\_wexitstatus ================== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_wexitstatus — Returns the return code of a terminated child ### Description ``` pcntl_wexitstatus(int $status): int|false ``` Returns the return code of a terminated child. This function is only useful if [pcntl\_wifexited()](function.pcntl-wifexited) returned **`true`**. ### Parameters `status` The `status` parameter is the status parameter supplied to a successful call to [pcntl\_waitpid()](function.pcntl-waitpid). ### Return Values Returns the return code. If the functionality is not supported by the OS, **`false`** is returned. ### See Also * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child * [pcntl\_wifexited()](function.pcntl-wifexited) - Checks if status code represents a normal exit php SplFileInfo::getInode SplFileInfo::getInode ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getInode — Gets the inode for the file ### Description ``` public SplFileInfo::getInode(): int|false ``` Gets the inode number for the filesystem object. ### Parameters This function has no parameters. ### Return Values Returns the inode number for the filesystem object on success, or **`false`** on failure. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) on error. ### See Also * [fileinode()](function.fileinode) - Gets file inode php stream_resolve_include_path stream\_resolve\_include\_path ============================== (PHP 5 >= 5.3.2, PHP 7, PHP 8) stream\_resolve\_include\_path — Resolve filename against the include path ### Description ``` stream_resolve_include_path(string $filename): string|false ``` Resolve `filename` against the include path according to the same rules as [fopen()](function.fopen)/[include](function.include). ### Parameters `filename` The filename to resolve. ### Return Values Returns a string containing the resolved absolute filename, or **`false`** on failure. ### Examples **Example #1 **stream\_resolve\_include\_path()** example** Basic usage example. ``` <?php var_dump(stream_resolve_include_path("test.php")); ?> ``` The above example will output something similar to: ``` string(22) "/var/www/html/test.php" ```
programming_docs
php session_register_shutdown session\_register\_shutdown =========================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) session\_register\_shutdown — Session shutdown function ### Description ``` session_register_shutdown(): void ``` Registers [session\_write\_close()](function.session-write-close) as a shutdown function. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Errors/Exceptions Emits **`E_WARNING`** if registering the shutdown function fails. php Phar::running Phar::running ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 2.0.0) Phar::running — Returns the full path on disk or full phar URL to the currently executing Phar archive ### Description ``` final public static Phar::running(bool $returnPhar = true): string ``` Returns the full path to the running phar archive. This is intended for use much like the `__FILE__` magic constant, and only has effect inside an executing phar archive. Inside the stub of an archive, **Phar::running()** returns `""`. Simply use **`__FILE__`** to access the current running phar inside a stub. ### Parameters `returnPhar` If **`false`**, the full path on disk to the phar archive is returned. If **`true`**, a full phar URL is returned. ### Return Values Returns the filename if valid, empty string otherwise. ### Examples **Example #1 A **Phar::running()** example** For the following example, assume the phar archive is located at `/path/to/phar/my.phar`. ``` <?php $a = Phar::running(); // $a is "phar:///path/to/my.phar" $b = Phar::running(false); // $b is "/path/to/my.phar" ?> ``` php hebrevc hebrevc ======= (PHP 4, PHP 5, PHP 7) hebrevc — Convert logical Hebrew text to visual text with newline conversion **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` hebrevc(string $hebrew_text, int $max_chars_per_line = 0): string ``` This function is similar to [hebrev()](function.hebrev) with the difference that it converts newlines (\n) to "<br>\n". The function tries to avoid breaking words. ### Parameters `hebrew_text` A Hebrew input string. `max_chars_per_line` This optional parameter indicates maximum number of characters per line that will be returned. ### Return Values Returns the visual string. ### See Also * [hebrev()](function.hebrev) - Convert logical Hebrew text to visual text php mysqli_stmt::prepare mysqli\_stmt::prepare ===================== mysqli\_stmt\_prepare ===================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::prepare -- mysqli\_stmt\_prepare — Prepares an SQL statement for execution ### Description Object-oriented style ``` public mysqli_stmt::prepare(string $query): bool ``` Procedural style ``` mysqli_stmt_prepare(mysqli_stmt $statement, string $query): bool ``` Prepares a statement for execution. The query must consist of a single SQL statement. The statement template can contain zero or more question mark (`?`) parameter markers⁠—also called placeholders. The parameter markers must be bound to application variables using [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) before executing the statement. > > **Note**: > > > In the case where a statement is passed to **mysqli\_stmt\_prepare()** that is longer than `max_allowed_packet` of the server, the returned error codes are different depending on whether you are using MySQL Native Driver (`mysqlnd`) or MySQL Client Library (`libmysqlclient`). The behavior is as follows: > > * `mysqlnd` on Linux returns an error code of 1153. The error message means got a packet bigger than `max_allowed_packet` bytes. > * `mysqlnd` on Windows returns an error code 2006. This error message means server has gone away. > * `libmysqlclient` on all platforms returns an error code 2006. This error message means server has gone away. > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). `query` The query, as a string. It must consist of a single SQL statement. The SQL statement may contain zero or more parameter markers represented by question mark (`?`) characters at the appropriate positions. > > **Note**: > > > The markers are legal only in certain places in SQL statements. For example, they are permitted in the `VALUES()` list of an `INSERT` statement (to specify column values for a row), or in a comparison with a column in a `WHERE` clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names). > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **mysqli\_stmt::prepare()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $city = "Amersfoort"; /* create a prepared statement */ $stmt = $mysqli->stmt_init(); $stmt->prepare("SELECT District FROM City WHERE Name=?"); /* bind parameters for markers */ $stmt->bind_param("s", $city); /* execute query */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($district); /* fetch value */ $stmt->fetch(); printf("%s is in district %s\n", $city, $district); ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $city = "Amersfoort"; /* create a prepared statement */ $stmt = mysqli_stmt_init($link); mysqli_stmt_prepare($stmt, "SELECT District FROM City WHERE Name=?"); /* bind parameters for markers */ mysqli_stmt_bind_param($stmt, "s", $city); /* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $district); /* fetch value */ mysqli_stmt_fetch($stmt); printf("%s is in district %s\n", $city, $district); ``` The above examples will output: ``` Amersfoort is in district Utrecht ``` ### See Also * [mysqli\_stmt\_init()](mysqli.stmt-init) - Initializes a statement and returns an object for use with mysqli\_stmt\_prepare * [mysqli\_stmt\_execute()](mysqli-stmt.execute) - Executes a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables * [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) - Binds variables to a prepared statement as parameters * [mysqli\_stmt\_bind\_result()](mysqli-stmt.bind-result) - Binds variables to a prepared statement for result storage * [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) - Gets a result set from a prepared statement as a mysqli\_result object * [mysqli\_stmt\_close()](mysqli-stmt.close) - Closes a prepared statement php eval eval ==== (PHP 4, PHP 5, PHP 7, PHP 8) eval — Evaluate a string as PHP code ### Description ``` eval(string $code): mixed ``` Evaluates the given `code` as PHP. **Caution** The **eval()** language construct is *very dangerous* because it allows execution of arbitrary PHP code. *Its use thus is discouraged.* If you have carefully verified that there is no other option than to use this construct, pay special attention *not to pass any user provided data* into it without properly validating it beforehand. ### Parameters `code` Valid PHP code to be evaluated. The code must not be wrapped in opening and closing [PHP tags](language.basic-syntax.phpmode), i.e. `'echo "Hi!";'` must be passed instead of `'<?php echo "Hi!"; ?>'`. It is still possible to leave and re-enter PHP mode though using the appropriate PHP tags, e.g. `'echo "In PHP mode!"; ?>In HTML mode!<?php echo "Back in PHP mode!";'`. Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon. `'echo "Hi!"'` for example will cause a parse error, whereas `'echo "Hi!";'` will work. A `return` statement will immediately terminate the evaluation of the code. The code will be executed in the scope of the code calling **eval()**. Thus any variables defined or changed in the **eval()** call will remain visible after it terminates. ### Return Values **eval()** returns **`null`** unless `return` is called in the evaluated code, in which case the value passed to `return` is returned. As of PHP 7, if there is a parse error in the evaluated code, **eval()** throws a ParseError exception. Before PHP 7, in this case **eval()** returned **`false`** and execution of the following code continued normally. It is not possible to catch a parse error in **eval()** using [set\_error\_handler()](function.set-error-handler). ### Examples **Example #1 **eval()** example - simple text merge** ``` <?php $string = 'cup'; $name = 'coffee'; $str = 'This is a $string with my $name in it.'; echo $str. "\n"; eval("\$str = \"$str\";"); echo $str. "\n"; ?> ``` The above example will output: ``` This is a $string with my $name in it. This is a cup with my coffee in it. ``` ### Notes > **Note**: Because this is a language construct and not a function, it cannot be called using [variable functions](functions.variable-functions), or [named arguments](functions.arguments#functions.named-arguments). > > **Tip**As with anything that outputs its result directly to the browser, the [output-control functions](https://www.php.net/manual/en/book.outcontrol.php) can be used to capture the output of this function, and save it in a string (for example). > > **Note**: > > > In case of a fatal error in the evaluated code, the whole script exits. > > ### See Also * [call\_user\_func()](function.call-user-func) - Call the callback given by the first parameter php InternalIterator::rewind InternalIterator::rewind ======================== (PHP 8) InternalIterator::rewind — Rewind the Iterator to the first element ### Description ``` public InternalIterator::rewind(): void ``` Rewinds back to the first element of the Iterator. ### Parameters This function has no parameters. ### Return Values No value is returned. php socket_recvmsg socket\_recvmsg =============== (PHP 5 >= 5.5.0, PHP 7, PHP 8) socket\_recvmsg — Read a message ### Description ``` socket_recvmsg(Socket $socket, array &$message, int $flags = 0): int|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `socket` `message` `flags` ### Return Values ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### See Also * [socket\_sendmsg()](function.socket-sendmsg) - Send a message * [socket\_cmsg\_space()](function.socket-cmsg-space) - Calculate message buffer size php The GdFont class The GdFont class ================ Introduction ------------ (PHP 8 >= 8.1.0) A fully opaque class which replaces `gd font` resources as of PHP 8.1.0. Class synopsis -------------- final class **GdFont** { } php fdf_errno fdf\_errno ========== (PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_errno — Return error code for last fdf operation ### Description ``` fdf_errno(): int ``` Gets the error code set by the last FDF function call. A textual description of the error may be obtained using with [fdf\_error()](function.fdf-error). ### Parameters This function has no parameters. ### Return Values Returns the error code as an integer, or zero if there was no errors. ### See Also * [fdf\_error()](function.fdf-error) - Return error description for FDF error code php SplFileInfo::getGroup SplFileInfo::getGroup ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getGroup — Gets the file group ### Description ``` public SplFileInfo::getGroup(): int|false ``` Gets the file group. The group ID is returned in numerical format. ### Parameters This function has no parameters. ### Return Values The group id in numerical format on success, or **`false`** on failure. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) on error. ### Examples **Example #1 **SplFileInfo::getGroup()** example** ``` <?php $info = new SplFileInfo(__FILE__); print_r(posix_getgrgid($info->getGroup())); ?> ``` The above example will output something similar to: ### See Also * [posix\_getgrgid()](function.posix-getgrgid) - Return info about a group by group id php shmop_delete shmop\_delete ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) shmop\_delete — Delete shared memory block ### Description ``` shmop_delete(Shmop $shmop): bool ``` **shmop\_delete()** is used to delete a shared memory block. ### Parameters `shmop` The shared memory block resource created by [shmop\_open()](function.shmop-open) ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `shmop` expects a [Shmop](class.shmop) instance now; previously, a resource was expected. | ### Examples **Example #1 Deleting shared memory block** ``` <?php shmop_delete($shm_id); ?> ``` This example will delete shared memory block identified by `$shm_id`. php gmp_div_r gmp\_div\_r =========== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_div\_r — Remainder of the division of numbers ### Description ``` gmp_div_r(GMP|int|string $num1, GMP|int|string $num2, int $rounding_mode = GMP_ROUND_ZERO): GMP ``` Calculates remainder of the integer division of `num1` by `num2`. The remainder has the sign of the `num1` argument, if not zero. ### Parameters `num1` The number being divided. A [GMP](class.gmp) object, an int or a numeric string. `num2` The number that `num1` is being divided by. A [GMP](class.gmp) object, an int or a numeric string. `rounding_mode` See the [gmp\_div\_q()](function.gmp-div-q) function for description of the `rounding_mode` argument. ### Return Values The remainder, as a GMP number. ### Examples **Example #1 **gmp\_div\_r()** example** ``` <?php $div = gmp_div_r("105", "20"); echo gmp_strval($div) . "\n"; ?> ``` The above example will output: ``` 5 ``` ### See Also * [gmp\_div\_q()](function.gmp-div-q) - Divide numbers * [gmp\_div\_qr()](function.gmp-div-qr) - Divide numbers and get quotient and remainder php DOMDocument::saveHTML DOMDocument::saveHTML ===================== (PHP 5, PHP 7, PHP 8) DOMDocument::saveHTML — Dumps the internal document into a string using HTML formatting ### Description ``` public DOMDocument::saveHTML(?DOMNode $node = null): string|false ``` Creates an HTML document from the DOM representation. This function is usually called after building a new dom document from scratch as in the example below. ### Parameters `node` Optional parameter to output a subset of the document. ### Return Values Returns the HTML, or **`false`** if an error occurred. ### Examples **Example #1 Saving a HTML tree into a string** ``` <?php $doc = new DOMDocument('1.0'); $root = $doc->createElement('html'); $root = $doc->appendChild($root); $head = $doc->createElement('head'); $head = $root->appendChild($head); $title = $doc->createElement('title'); $title = $head->appendChild($title); $text = $doc->createTextNode('This is the title'); $text = $title->appendChild($text); echo $doc->saveHTML(); ?> ``` ### See Also * [DOMDocument::saveHTMLFile()](domdocument.savehtmlfile) - Dumps the internal document into a file using HTML formatting * [DOMDocument::loadHTML()](domdocument.loadhtml) - Load HTML from a string * [DOMDocument::loadHTMLFile()](domdocument.loadhtmlfile) - Load HTML from a file php imap_fetchheader imap\_fetchheader ================= (PHP 4, PHP 5, PHP 7, PHP 8) imap\_fetchheader — Returns header for a message ### Description ``` imap_fetchheader(IMAP\Connection $imap, int $message_num, int $flags = 0): string|false ``` This function causes a fetch of the complete, unfiltered [» RFC2822](http://www.faqs.org/rfcs/rfc2822) format header of the specified message. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_num` The message number `flags` The possible `flags` are: * **`FT_UID`** - The `message_num` argument is a UID * **`FT_INTERNAL`** - The return string is in "internal" format, without any attempt to canonicalize to CRLF newlines * **`FT_PREFETCHTEXT`** - The RFC822.TEXT should be pre-fetched at the same time. This avoids an extra RTT on an IMAP connection if a full message text is desired (e.g. in a "save to local file" operation) ### Return Values Returns the header of the specified message as a text string, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_fetch\_overview()](function.imap-fetch-overview) - Read an overview of the information in the headers of the given message php Iterator::current Iterator::current ================= (PHP 5, PHP 7, PHP 8) Iterator::current — Return the current element ### Description ``` public Iterator::current(): mixed ``` Returns the current element. ### Parameters This function has no parameters. ### Return Values Can return any type. php shm_has_var shm\_has\_var ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8) shm\_has\_var — Check whether a specific entry exists ### Description ``` shm_has_var(SysvSharedMemory $shm, int $key): bool ``` Checks whether a specific key exists inside a shared memory segment. ### Parameters `shm` A shared memory segment obtained from [shm\_attach()](function.shm-attach). `key` The variable key. ### Return Values Returns **`true`** if the entry exists, otherwise **`false`** ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `shm` expects a [SysvSharedMemory](class.sysvsharedmemory) instance now; previously, a resource was expected. | ### See Also * [shm\_get\_var()](function.shm-get-var) - Returns a variable from shared memory * [shm\_put\_var()](function.shm-put-var) - Inserts or updates a variable in shared memory php The Yaf_Config_Ini class The Yaf\_Config\_Ini class ========================== Introduction ------------ (Yaf >=1.0.0) Yaf\_Config\_Ini enables developers to store configuration data in a familiar INI format and read them in the application by using nested object property syntax. The INI format is specialized to provide both the ability to have a hierarchy of configuration data keys and inheritance between configuration data sections. Configuration data hierarchies are supported by separating the keys with the dot or period character ("."). A section may extend or inherit from another section by following the section name with a colon character (":") and the name of the section from which data are to be inherited. > > **Note**: > > > Yaf\_Config\_Ini utilizes the » parse\_ini\_file() PHP function. Please review this documentation to be aware of its specific behaviors, which propagate to Yaf\_Config\_Ini, such as how the special values of "**`true`**", "**`false`**", "yes", "no", and "**`null`**" are handled. > > Class synopsis -------------- class **Yaf\_Config\_Ini** extends [Yaf\_Config\_Abstract](class.yaf-config-abstract) implements [Iterator](class.iterator), [ArrayAccess](class.arrayaccess), [Countable](class.countable) { /\* Properties \*/ /\* Methods \*/ public [\_\_construct](yaf-config-ini.construct)(string `$config_file`, string `$section` = ?) ``` public count(): void ``` ``` public current(): void ``` ``` public __get(string $name = ?): void ``` ``` public __isset(string $name): void ``` ``` public key(): void ``` ``` public next(): void ``` ``` public offsetExists(string $name): void ``` ``` public offsetGet(string $name): void ``` ``` public offsetSet(string $name, string $value): void ``` ``` public offsetUnset(string $name): void ``` ``` public readonly(): void ``` ``` public rewind(): void ``` ``` public __set(string $name, mixed $value): void ``` ``` public toArray(): array ``` ``` public valid(): void ``` /\* Inherited methods \*/ ``` abstract public Yaf_Config_Abstract::get(string $name, mixed $value): mixed ``` ``` abstract public Yaf_Config_Abstract::readonly(): bool ``` ``` abstract public Yaf_Config_Abstract::set(): Yaf_Config_Abstract ``` ``` abstract public Yaf_Config_Abstract::toArray(): array ``` } Properties ---------- \_config \_readonly Examples -------- **Example #1 **Yaf\_Config\_Ini()**example** This example illustrates a basic use of Yaf\_Config\_Ini for loading configuration data from an INI file. In this example there are configuration data for both a production system and for a staging system. Because the staging system configuration data are very similar to those for production, the staging section inherits from the production section. In this case, the decision is arbitrary and could have been written conversely, with the production section inheriting from the staging section, though this may not be the case for more complex situations. Suppose, then, that the following configuration data are contained in /path/to/config.ini: ``` ; Production site configuration data [production] webhost = www.example.com database.adapter = pdo_mysql database.params.host = db.example.com database.params.username = dbuser database.params.password = secret database.params.dbname = dbname ; Staging site configuration data inherits from production and ; overrides values as necessary [staging : production] database.params.host = dev.example.com database.params.username = devuser database.params.password = devsecret ``` ``` <?php $config = new Yaf_Config_Ini('/path/to/config.ini', 'staging');   var_dump($config->database->params->host);  var_dump($config->database->params->dbname); var_dump($config->get("database.params.username")); ?> ``` The above example will output something similar to: ``` string(15) "dev.example.com" string(6) "dbname" string(7) "devuser ``` Table of Contents ----------------- * [Yaf\_Config\_Ini::\_\_construct](yaf-config-ini.construct) — Yaf\_Config\_Ini constructor * [Yaf\_Config\_Ini::count](yaf-config-ini.count) — Count all elements in Yaf\_Config.ini * [Yaf\_Config\_Ini::current](yaf-config-ini.current) — Retrieve the current value * [Yaf\_Config\_Ini::\_\_get](yaf-config-ini.get) — Retrieve a element * [Yaf\_Config\_Ini::\_\_isset](yaf-config-ini.isset) — Determine if a key is exists * [Yaf\_Config\_Ini::key](yaf-config-ini.key) — Fetch current element's key * [Yaf\_Config\_Ini::next](yaf-config-ini.next) — Advance the internal pointer * [Yaf\_Config\_Ini::offsetExists](yaf-config-ini.offsetexists) — The offsetExists purpose * [Yaf\_Config\_Ini::offsetGet](yaf-config-ini.offsetget) — The offsetGet purpose * [Yaf\_Config\_Ini::offsetSet](yaf-config-ini.offsetset) — The offsetSet purpose * [Yaf\_Config\_Ini::offsetUnset](yaf-config-ini.offsetunset) — The offsetUnset purpose * [Yaf\_Config\_Ini::readonly](yaf-config-ini.readonly) — The readonly purpose * [Yaf\_Config\_Ini::rewind](yaf-config-ini.rewind) — The rewind purpose * [Yaf\_Config\_Ini::\_\_set](yaf-config-ini.set) — The \_\_set purpose * [Yaf\_Config\_Ini::toArray](yaf-config-ini.toarray) — Return config as a PHP array * [Yaf\_Config\_Ini::valid](yaf-config-ini.valid) — The valid purpose
programming_docs
php Yaf_Loader::registerLocalNamespace Yaf\_Loader::registerLocalNamespace =================================== (Yaf >=1.0.0) Yaf\_Loader::registerLocalNamespace — Register local class prefix ### Description ``` public Yaf_Loader::registerLocalNamespace(mixed $prefix): void ``` Register local class prefix name, [Yaf\_Loader](class.yaf-loader) search classes in two library directories, the one is configured via [application.library.directory](https://www.php.net/manual/en/yaf.appconfig.php#configuration.yaf.library)(in application.ini) which is called local libraray directory; the other is configured via [yaf.library](https://www.php.net/manual/en/yaf.configuration.php#ini.yaf.library) (in php.ini) which is callled global library directory, since it can be shared by many applications in the same server. When an autloading is trigger, [Yaf\_Loader](class.yaf-loader) will determine which library directory should be searched in by exame the prefix name of the missed classname. If the prefix name is registered as a localnamespack then look for it in local library directory, otherwise look for it in global library directory. > > **Note**: > > > If yaf.library is not configured, then the global library directory is assumed to be the local library directory. in that case, all autoloading will look for local library directory. But if you want your Yaf application be strong, then always register your own classes as local classes. > > ### Parameters `prefix` a string or a array of class name prefix. all class prefix with these prefix will be loaded in local library path. ### Return Values bool ### Examples **Example #1 **Yaf\_Loader::registerLocalNamespace()**example** ``` <?php $loader = Yaf_Loader::getInstance('/local/library/', '/global/library'); $loader->registerLocalNamespace("Baidu"); $loader->registerLocalNamespace(array("Sina", "Weibo")); $loader->autoload("Baidu_Name"); // search in '/local/library/' $loader->autoload("Sina");       // search '/local/library/' $loader->autoload("Global_Name");// search in '/global/library/' $loader->autoload("Foo_Bar");    // search in '/global/library/' ?> ``` php imap_thread imap\_thread ============ (PHP 4 >= 4.0.7, PHP 5, PHP 7, PHP 8) imap\_thread — Returns a tree of threaded message ### Description ``` imap_thread(IMAP\Connection $imap, int $flags = SE_FREE): array|false ``` Gets a tree of a threaded message. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `flags` ### Return Values **imap\_thread()** returns an associative array containing a tree of messages threaded by `REFERENCES`, or **`false`** on error. Every message in the current mailbox will be represented by three entries in the resulting array: * $thread["XX.num"] - current message number * $thread["XX.next"] * $thread["XX.branch"] ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_thread()** Example** ``` <?php // Here we're outputting the threads of a newsgroup, in HTML $nntp = imap_open('{news.example.com:119/nntp}some.newsgroup', '', ''); $threads = imap_thread($nntp); foreach ($threads as $key => $val) {   $tree = explode('.', $key);   if ($tree[1] == 'num') {     $header = imap_headerinfo($nntp, $val);     echo "<ul>\n\t<li>" . $header->fromaddress . "\n";   } elseif ($tree[1] == 'branch') {     echo "\t</li>\n</ul>\n";   } } imap_close($nntp); ?> ``` php pg_send_query_params pg\_send\_query\_params ======================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) pg\_send\_query\_params — Submits a command and separate parameters to the server without waiting for the result(s) ### Description ``` pg_send_query_params(PgSql\Connection $connection, string $query, array $params): int|bool ``` Submits a command and separate parameters to the server without waiting for the result(s). This is equivalent to [pg\_send\_query()](function.pg-send-query) except that query parameters can be specified separately from the `query` string. The function's parameters are handled identically to [pg\_query\_params()](function.pg-query-params). Like [pg\_query\_params()](function.pg-query-params), it will not work on pre-7.4 PostgreSQL connections, and it allows only one command in the query string. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. `query` The parameterized SQL statement. Must contain only a single statement. (multiple statements separated by semi-colons are not allowed.) If any parameters are used, they are referred to as $1, $2, etc. `params` An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders. ### Return Values Returns **`true`** on success, **`false`** or `0` on failure. Use [pg\_get\_result()](function.pg-get-result) to determine the query result. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Using **pg\_send\_query\_params()**** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   // Using parameters.  Note that it is not necessary to quote or escape   // the parameter.   pg_send_query_params($dbconn, 'select count(*) from authors where city = $1', array('Perth'));      // Compare against basic pg_send_query usage   $str = pg_escape_string('Perth');   pg_send_query($dbconn, "select count(*) from authors where city = '${str}'"); ?> ``` ### See Also * [pg\_send\_query()](function.pg-send-query) - Sends asynchronous query php streamWrapper::stream_write streamWrapper::stream\_write ============================ (PHP 4 >= 4.3.2, PHP 5, PHP 7, PHP 8) streamWrapper::stream\_write — Write to stream ### Description ``` public streamWrapper::stream_write(string $data): int ``` This method is called in response to [fwrite()](function.fwrite). > > **Note**: > > > Remember to update the current position of the stream by number of bytes that were successfully written. > > ### Parameters `data` Should be stored into the underlying stream. > > **Note**: > > > If there is not enough room in the underlying stream, store as much as possible. > > ### Return Values Should return the number of bytes that were successfully stored, or 0 if none could be stored. ### Errors/Exceptions Emits **`E_WARNING`** if call to this method fails (i.e. not implemented). > > **Note**: > > > If the return value is greater the length of `data`, **`E_WARNING`** will be emitted and the return value will truncated to its length. > > ### See Also * [fwrite()](function.fwrite) - Binary-safe file write php The UConverter class The UConverter class ==================== Introduction ------------ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) Class synopsis -------------- class **UConverter** { /\* Constants \*/ public const int [REASON\_UNASSIGNED](class.uconverter#uconverter.constants.reason-unassigned); public const int [REASON\_ILLEGAL](class.uconverter#uconverter.constants.reason-illegal); public const int [REASON\_IRREGULAR](class.uconverter#uconverter.constants.reason-irregular); public const int [REASON\_RESET](class.uconverter#uconverter.constants.reason-reset); public const int [REASON\_CLOSE](class.uconverter#uconverter.constants.reason-close); public const int [REASON\_CLONE](class.uconverter#uconverter.constants.reason-clone); public const int [UNSUPPORTED\_CONVERTER](class.uconverter#uconverter.constants.unsupported-converter); public const int [SBCS](class.uconverter#uconverter.constants.sbcs); public const int [DBCS](class.uconverter#uconverter.constants.dbcs); public const int [MBCS](class.uconverter#uconverter.constants.mbcs); public const int [LATIN\_1](class.uconverter#uconverter.constants.latin-1); public const int [UTF8](class.uconverter#uconverter.constants.utf8); public const int [UTF16\_BigEndian](class.uconverter#uconverter.constants.utf16-bigendian); public const int [UTF16\_LittleEndian](class.uconverter#uconverter.constants.utf16-littleendian); public const int [UTF32\_BigEndian](class.uconverter#uconverter.constants.utf32-bigendian); public const int [UTF32\_LittleEndian](class.uconverter#uconverter.constants.utf32-littleendian); public const int [EBCDIC\_STATEFUL](class.uconverter#uconverter.constants.ebcdic-stateful); public const int [ISO\_2022](class.uconverter#uconverter.constants.iso-2022); public const int [LMBCS\_1](class.uconverter#uconverter.constants.lmbcs-1); public const int [LMBCS\_2](class.uconverter#uconverter.constants.lmbcs-2); public const int [LMBCS\_3](class.uconverter#uconverter.constants.lmbcs-3); public const int [LMBCS\_4](class.uconverter#uconverter.constants.lmbcs-4); public const int [LMBCS\_5](class.uconverter#uconverter.constants.lmbcs-5); public const int [LMBCS\_6](class.uconverter#uconverter.constants.lmbcs-6); public const int [LMBCS\_8](class.uconverter#uconverter.constants.lmbcs-8); public const int [LMBCS\_11](class.uconverter#uconverter.constants.lmbcs-11); public const int [LMBCS\_16](class.uconverter#uconverter.constants.lmbcs-16); public const int [LMBCS\_17](class.uconverter#uconverter.constants.lmbcs-17); public const int [LMBCS\_18](class.uconverter#uconverter.constants.lmbcs-18); public const int [LMBCS\_19](class.uconverter#uconverter.constants.lmbcs-19); public const int [LMBCS\_LAST](class.uconverter#uconverter.constants.lmbcs-last); public const int [HZ](class.uconverter#uconverter.constants.hz); public const int [SCSU](class.uconverter#uconverter.constants.scsu); public const int [ISCII](class.uconverter#uconverter.constants.iscii); public const int [US\_ASCII](class.uconverter#uconverter.constants.us-ascii); public const int [UTF7](class.uconverter#uconverter.constants.utf7); public const int [BOCU1](class.uconverter#uconverter.constants.bocu1); public const int [UTF16](class.uconverter#uconverter.constants.utf16); public const int [UTF32](class.uconverter#uconverter.constants.utf32); public const int [CESU8](class.uconverter#uconverter.constants.cesu8); public const int [IMAP\_MAILBOX](class.uconverter#uconverter.constants.imap-mailbox); /\* Methods \*/ public [\_\_construct](uconverter.construct)(?string `$destination_encoding` = **`null`**, ?string `$source_encoding` = **`null`**) ``` public convert(string $str, bool $reverse = false): string|false ``` ``` public fromUCallback( int $reason, array $source, int $codePoint, int &$error ): string|int|array|null ``` ``` public static getAliases(string $name): array|false|null ``` ``` public static getAvailable(): array ``` ``` public getDestinationEncoding(): string|false|null ``` ``` public getDestinationType(): int|false|null ``` ``` public getErrorCode(): int ``` ``` public getErrorMessage(): ?string ``` ``` public getSourceEncoding(): string|false|null ``` ``` public getSourceType(): int|false|null ``` ``` public static getStandards(): ?array ``` ``` public getSubstChars(): string|false|null ``` ``` public static reasonText(int $reason): string ``` ``` public setDestinationEncoding(string $encoding): bool ``` ``` public setSourceEncoding(string $encoding): bool ``` ``` public setSubstChars(string $chars): bool ``` ``` public toUCallback( int $reason, string $source, string $codeUnits, int &$error ): string|int|array|null ``` ``` public static transcode( string $str, string $toEncoding, string $fromEncoding, ?array $options = null ): string|false ``` } Predefined Constants -------------------- **`UConverter::REASON_UNASSIGNED`** **`UConverter::REASON_ILLEGAL`** **`UConverter::REASON_IRREGULAR`** **`UConverter::REASON_RESET`** **`UConverter::REASON_CLOSE`** **`UConverter::REASON_CLONE`** **`UConverter::UNSUPPORTED_CONVERTER`** **`UConverter::SBCS`** **`UConverter::DBCS`** **`UConverter::MBCS`** **`UConverter::LATIN_1`** **`UConverter::UTF8`** **`UConverter::UTF16_BigEndian`** **`UConverter::UTF16_LittleEndian`** **`UConverter::UTF32_BigEndian`** **`UConverter::UTF32_LittleEndian`** **`UConverter::EBCDIC_STATEFUL`** **`UConverter::ISO_2022`** **`UConverter::LMBCS_1`** **`UConverter::LMBCS_2`** **`UConverter::LMBCS_3`** **`UConverter::LMBCS_4`** **`UConverter::LMBCS_5`** **`UConverter::LMBCS_6`** **`UConverter::LMBCS_8`** **`UConverter::LMBCS_11`** **`UConverter::LMBCS_16`** **`UConverter::LMBCS_17`** **`UConverter::LMBCS_18`** **`UConverter::LMBCS_19`** **`UConverter::LMBCS_LAST`** **`UConverter::HZ`** **`UConverter::SCSU`** **`UConverter::ISCII`** **`UConverter::US_ASCII`** **`UConverter::UTF7`** **`UConverter::BOCU1`** **`UConverter::UTF16`** **`UConverter::UTF32`** **`UConverter::CESU8`** **`UConverter::IMAP_MAILBOX`** Table of Contents ----------------- * [UConverter::\_\_construct](uconverter.construct) — Create UConverter object * [UConverter::convert](uconverter.convert) — Convert string from one charset to another * [UConverter::fromUCallback](uconverter.fromucallback) — Default "from" callback function * [UConverter::getAliases](uconverter.getaliases) — Get the aliases of the given name * [UConverter::getAvailable](uconverter.getavailable) — Get the available canonical converter names * [UConverter::getDestinationEncoding](uconverter.getdestinationencoding) — Get the destination encoding * [UConverter::getDestinationType](uconverter.getdestinationtype) — Get the destination converter type * [UConverter::getErrorCode](uconverter.geterrorcode) — Get last error code on the object * [UConverter::getErrorMessage](uconverter.geterrormessage) — Get last error message on the object * [UConverter::getSourceEncoding](uconverter.getsourceencoding) — Get the source encoding * [UConverter::getSourceType](uconverter.getsourcetype) — Get the source converter type * [UConverter::getStandards](uconverter.getstandards) — Get standards associated to converter names * [UConverter::getSubstChars](uconverter.getsubstchars) — Get substitution chars * [UConverter::reasonText](uconverter.reasontext) — Get string representation of the callback reason * [UConverter::setDestinationEncoding](uconverter.setdestinationencoding) — Set the destination encoding * [UConverter::setSourceEncoding](uconverter.setsourceencoding) — Set the source encoding * [UConverter::setSubstChars](uconverter.setsubstchars) — Set the substitution chars * [UConverter::toUCallback](uconverter.toucallback) — Default "to" callback function * [UConverter::transcode](uconverter.transcode) — Convert a string from one character encoding to another php None Covariance and Contravariance ----------------------------- In PHP 7.2.0, partial contravariance was introduced by removing type restrictions on parameters in a child method. As of PHP 7.4.0, full covariance and contravariance support was added. Covariance allows a child's method to return a more specific type than the return type of its parent's method. Whereas, contravariance allows a parameter type to be less specific in a child method, than that of its parent. A type declaration is considered more specific in the following case: * A type is removed from a [union type](language.types.type-system#language.types.type-system.composite.union) * A type is added to an [intersection type](language.types.type-system#language.types.type-system.composite.intersection) * A class type is changed to a child class type * [iterable](language.types.iterable) is changed to array or [Traversable](class.traversable) A type class is considered less specific if the opposite is true. ### Covariance To illustrate how covariance works, a simple abstract parent class, Animal is created. Animal will be extended by children classes, Cat, and Dog. ``` <?php abstract class Animal {     protected string $name;     public function __construct(string $name)     {         $this->name = $name;     }     abstract public function speak(); } class Dog extends Animal {     public function speak()     {         echo $this->name . " barks";     } } class Cat extends Animal  {     public function speak()     {         echo $this->name . " meows";     } } ``` Note that there aren't any methods which return values in this example. A few factories will be added which return a new object of class type Animal, Cat, or Dog. ``` <?php interface AnimalShelter {     public function adopt(string $name): Animal; } class CatShelter implements AnimalShelter {     public function adopt(string $name): Cat // instead of returning class type Animal, it can return class type Cat     {         return new Cat($name);     } } class DogShelter implements AnimalShelter {     public function adopt(string $name): Dog // instead of returning class type Animal, it can return class type Dog     {         return new Dog($name);     } } $kitty = (new CatShelter)->adopt("Ricky"); $kitty->speak(); echo "\n"; $doggy = (new DogShelter)->adopt("Mavrick"); $doggy->speak(); ``` The above example will output: ``` Ricky meows Mavrick barks ``` ### Contravariance Continuing with the previous example with the classes Animal, Cat, and Dog, a class called Food and AnimalFood will be included, and a method eat(AnimalFood $food) is added to the Animal abstract class. ``` <?php class Food {} class AnimalFood extends Food {} abstract class Animal {     protected string $name;     public function __construct(string $name)     {         $this->name = $name;     }     public function eat(AnimalFood $food)     {         echo $this->name . " eats " . get_class($food);     } } ``` In order to see the behavior of contravariance, the eat method is overridden in the Dog class to allow any Food type object. The Cat class remains unchanged. ``` <?php class Dog extends Animal {     public function eat(Food $food) {         echo $this->name . " eats " . get_class($food);     } } ``` The next example will show the behavior of contravariance. ``` <?php $kitty = (new CatShelter)->adopt("Ricky"); $catFood = new AnimalFood(); $kitty->eat($catFood); echo "\n"; $doggy = (new DogShelter)->adopt("Mavrick"); $banana = new Food(); $doggy->eat($banana); ``` The above example will output: ``` Ricky eats AnimalFood Mavrick eats Food ``` But what happens if $kitty tries to eat the $banana? ``` $kitty->eat($banana); ``` The above example will output: ``` Fatal error: Uncaught TypeError: Argument 1 passed to Animal::eat() must be an instance of AnimalFood, instance of Food given ``` php EventHttpRequest::getUri EventHttpRequest::getUri ======================== (PECL event >= 1.4.0-beta) EventHttpRequest::getUri — Returns the request URI ### Description ``` public EventHttpRequest::getUri(): string ``` Returns the request URI ### Parameters This function has no parameters. ### Return Values Returns the request URI ### See Also * [EventHttpRequest::getCommand()](eventhttprequest.getcommand) - Returns the request command(method) * [EventHttpRequest::getHost()](eventhttprequest.gethost) - Returns the request host * [EventHttpRequest::getResponseCode()](eventhttprequest.getresponsecode) - Returns the response code php Ds\Queue::toArray Ds\Queue::toArray ================= (PECL ds >= 1.0.0) Ds\Queue::toArray — Converts the queue to an array ### Description ``` public Ds\Queue::toArray(): array ``` Converts the queue to an array. > > **Note**: > > > Casting to an array is not supported yet. > > > > **Note**: > > > This method is not destructive. > > ### Parameters This function has no parameters. ### Return Values An array containing all the values in the same order as the queue. ### Examples **Example #1 **Ds\Queue::toArray()** example** ``` <?php $queue = new \Ds\Queue([1, 2, 3]); var_dump($queue->toArray()); ?> ``` The above example will output something similar to: ``` array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ```
programming_docs
php stats_covariance stats\_covariance ================= (PECL stats >= 1.0.0) stats\_covariance — Computes the covariance of two data sets ### Description ``` stats_covariance(array $a, array $b): float ``` Returns the covariance of `a` and `b`. ### Parameters `a` The first array `b` The second array ### Return Values Returns the covariance of `a` and `b`, or **`false`** on failure. php PharFileInfo::setMetadata PharFileInfo::setMetadata ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) PharFileInfo::setMetadata — Sets file-specific meta-data saved with a file ### Description ``` public PharFileInfo::setMetadata(mixed $metadata): void ``` **PharFileInfo::setMetadata()** should only be used to store customized data in a file that cannot be represented with existing information stored with a file. Meta-data can significantly slow down the performance of loading a phar archive if the data is large, or if there are many files containing meta-data. It is important to note that file permissions are natively supported inside a phar; it is possible to set them with the [PharFileInfo::chmod()](pharfileinfo.chmod) method. As with all functionality that modifies the contents of a phar, the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable must be off in order to succeed if the file is within a [Phar](class.phar) archive. Files within [PharData](class.phardata) archives do not have this restriction. Some possible uses for meta-data include passing a user/group that should be set when a file is extracted from the phar to disk. Other uses could include explicitly specifying a MIME type to return. However, any useful data that describes a file, but should not be contained inside of it may be stored. ### Parameters `metadata` Any PHP variable containing information to store alongside a file ### Return Values No value is returned. ### Examples **Example #1 A **PharFileInfo::setMetadata()** example** ``` <?php // make sure it doesn't exist @unlink('brandnewphar.phar'); try {     $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar');     $p['file.txt'] = 'hello';     $p['file.txt']->setMetadata(array('user' => 'bill', 'mime-type' => 'text/plain'));     var_dump($p['file.txt']->getMetaData()); } catch (Exception $e) {     echo 'Could not create/modify phar: ', $e; } ?> ``` The above example will output: ``` array(2) { ["user"]=> string(4) "bill" ["mime-type"]=> string(10) "text/plain" } ``` ### See Also * [PharFileInfo::hasMetadata()](pharfileinfo.hasmetadata) - Returns the metadata of the entry * [PharFileInfo::getMetadata()](pharfileinfo.getmetadata) - Returns file-specific meta-data saved with a file * [PharFileInfo::delMetadata()](pharfileinfo.delmetadata) - Deletes the metadata of the entry * [Phar::setMetadata()](phar.setmetadata) - Sets phar archive meta-data * [Phar::hasMetadata()](phar.hasmetadata) - Returns whether phar has global meta-data * [Phar::getMetadata()](phar.getmetadata) - Returns phar archive meta-data php Ds\Vector::pop Ds\Vector::pop ============== (PECL ds >= 1.0.0) Ds\Vector::pop — Removes and returns the last value ### Description ``` public Ds\Vector::pop(): mixed ``` Removes and returns the last value. ### Parameters This function has no parameters. ### Return Values The removed last value. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Vector::pop()** example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); var_dump($vector->pop()); var_dump($vector->pop()); var_dump($vector->pop()); ?> ``` The above example will output something similar to: ``` int(3) int(2) int(1) ``` php enchant_broker_dict_exists enchant\_broker\_dict\_exists ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_broker\_dict\_exists — Whether a dictionary exists or not. Using non-empty tag ### Description ``` enchant_broker_dict_exists(EnchantBroker $broker, string $tag): bool ``` Tells if a dictionary exists or not, using a non-empty tags ### Parameters `broker` An Enchant broker returned by [enchant\_broker\_init()](function.enchant-broker-init). `tag` non-empty tag in the LOCALE format, ex: us\_US, ch\_DE, etc. ### Return Values Returns **`true`** when the tag exist or **`false`** when not. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `broker` expects an [EnchantBroker](class.enchantbroker) instance now; previoulsy, a [resource](language.types.resource) was expected. | ### Examples **Example #1 A **enchant\_broker\_dict\_exists()** example** ``` <?php $tag = 'en_US'; $r = enchant_broker_init(); if (enchant_broker_dict_exists($r,$tag)) {     echo $tag . " dictionary found.\n"; } ?> ``` ### See Also * [enchant\_broker\_describe()](function.enchant-broker-describe) - Enumerates the Enchant providers php SolrQuery::getHighlightFields SolrQuery::getHighlightFields ============================= (PECL solr >= 0.9.2) SolrQuery::getHighlightFields — Returns all the fields that Solr should generate highlighted snippets for ### Description ``` public SolrQuery::getHighlightFields(): array ``` Returns all the fields that Solr should generate highlighted snippets for ### Parameters This function has no parameters. ### Return Values Returns an array on success and **`null`** if not set. php Ds\Sequence::merge Ds\Sequence::merge ================== (PECL ds >= 1.0.0) Ds\Sequence::merge — Returns the result of adding all given values to the sequence ### Description ``` abstract public Ds\Sequence::merge(mixed $values): Ds\Sequence ``` Returns the result of adding all given values to the sequence. ### Parameters `values` A [traversable](class.traversable) object or an array. ### Return Values The result of adding all given values to the sequence, effectively the same as adding the values to a copy, then returning that copy. > > **Note**: > > > The current instance won't be affected. > > ### Examples **Example #1 **Ds\Sequence::merge()** example** ``` <?php $sequence = new \Ds\Vector([1, 2, 3]); var_dump($sequence->merge([4, 5, 6])); var_dump($sequence); ?> ``` The above example will output something similar to: ``` object(Ds\Vector)#2 (6) { [0]=> int(1) [1]=> int(2) [2]=> int(3) [3]=> int(4) [4]=> int(5) [5]=> int(6) } object(Ds\Vector)#1 (3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ``` php print_r print\_r ======== (PHP 4, PHP 5, PHP 7, PHP 8) print\_r — Prints human-readable information about a variable ### Description ``` print_r(mixed $value, bool $return = false): string|bool ``` **print\_r()** displays information about a variable in a way that's readable by humans. **print\_r()**, [var\_dump()](function.var-dump) and [var\_export()](function.var-export) will also show protected and private properties of objects. Static class members will not be shown. ### Parameters `value` The expression to be printed. `return` If you would like to capture the output of **print\_r()**, use the `return` parameter. When this parameter is set to **`true`**, **print\_r()** will return the information rather than print it. ### Return Values If given a string, int or float, the value itself will be printed. If given an array, values will be presented in a format that shows keys and elements. Similar notation is used for objects. When the `return` parameter is **`true`**, this function will return a string. Otherwise, the return value is **`true`**. ### Examples **Example #1 **print\_r()** example** ``` <pre> <?php $a = array ('a' => 'apple', 'b' => 'banana', 'c' => array ('x', 'y', 'z')); print_r ($a); ?> </pre> ``` The above example will output: ``` <pre> Array ( [a] => apple [b] => banana [c] => Array ( [0] => x [1] => y [2] => z ) ) </pre> ``` **Example #2 `return` parameter example** ``` <?php $b = array ('m' => 'monkey', 'foo' => 'bar', 'x' => array ('x', 'y', 'z')); $results = print_r($b, true); // $results now contains output from print_r ?> ``` ### Notes > > **Note**: > > > When the `return` parameter is used, this function uses internal output buffering prior to PHP 7.1.0, so it cannot be used inside an [ob\_start()](function.ob-start) callback function. > > > ### See Also * [ob\_start()](function.ob-start) - Turn on output buffering * [var\_dump()](function.var-dump) - Dumps information about a variable * [var\_export()](function.var-export) - Outputs or returns a parsable string representation of a variable php SQLite3::changes SQLite3::changes ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3::changes — Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement ### Description ``` public SQLite3::changes(): int ``` Returns the number of database rows that were changed (or inserted or deleted) by the most recent SQL statement. ### Parameters This function has no parameters. ### Return Values Returns an int value corresponding to the number of database rows changed (or inserted or deleted) by the most recent SQL statement. ### Examples **Example #1 **SQLite3::changes()** example** ``` <?php $db = new SQLite3('mysqlitedb.db'); $query = $db->exec('UPDATE counter SET views=0 WHERE page="test"'); if ($query) {     echo 'Number of rows modified: ', $db->changes(); } ?> ``` php SplDoublyLinkedList::bottom SplDoublyLinkedList::bottom =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::bottom — Peeks at the node from the beginning of the doubly linked list ### Description ``` public SplDoublyLinkedList::bottom(): mixed ``` ### Parameters This function has no parameters. ### Return Values The value of the first node. ### Errors/Exceptions Throws [RuntimeException](class.runtimeexception) when the data-structure is empty. php EventBuffer::prependBuffer EventBuffer::prependBuffer ========================== (PECL event >= 1.2.6-beta) EventBuffer::prependBuffer — Moves all data from source buffer to the front of current buffer ### Description ``` public EventBuffer::prependBuffer( EventBuffer $buf ): bool ``` Behaves as [EventBuffer::addBuffer()](eventbuffer.addbuffer) , except that it moves data to the front of the buffer. ### Parameters `buf` Source buffer. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBuffer::add()](eventbuffer.add) - Append data to the end of an event buffer * [EventBuffer::addBuffer()](eventbuffer.addbuffer) - Move all data from a buffer provided to the current instance of EventBuffer * [EventBuffer::prepend()](eventbuffer.prepend) - Prepend data to the front of the buffer php OAuthProvider::consumerHandler OAuthProvider::consumerHandler ============================== (PECL OAuth >= 1.0.0) OAuthProvider::consumerHandler — Set the consumerHandler handler callback ### Description ``` public OAuthProvider::consumerHandler(callable $callback_function): void ``` Sets the consumer handler callback, which will later be called with [OAuthProvider::callConsumerHandler()](oauthprovider.callconsumerhandler). **Warning**This function is currently not documented; only its argument list is available. ### Parameters `callback_function` The [callable](language.types.callable) functions name. ### Return Values No value is returned. ### Examples **Example #1 Example **OAuthProvider::consumerHandler()** callback** ``` <?php function lookupConsumer($provider) {     if ($provider->consumer_key === 'unknown') {         return OAUTH_CONSUMER_KEY_UNKNOWN;     } else if($provider->consumer_key == 'blacklisted' || $provider->consumer_key === 'throttled') {         return OAUTH_CONSUMER_KEY_REFUSED;     }     $provider->consumer_secret = "the_consumers_secret";     return OAUTH_OK; } ?> ``` ### See Also * [OAuthProvider::callConsumerHandler()](oauthprovider.callconsumerhandler) - Calls the consumerNonceHandler callback php Ds\Queue::jsonSerialize Ds\Queue::jsonSerialize ======================= (PECL ds >= 1.0.0) Ds\Queue::jsonSerialize — Returns a representation that can be converted to JSON See [JsonSerializable::jsonSerialize()](jsonserializable.jsonserialize) > > **Note**: > > > You should never need to call this directly. > > php Phar::loadPhar Phar::loadPhar ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::loadPhar — Loads any phar archive with an alias ### Description ``` final public static Phar::loadPhar(string $filename, ?string $alias = null): bool ``` This can be used to read the contents of an external Phar archive. This is most useful for assigning an alias to a phar so that subsequent references to the phar can use the shorter alias, or for loading Phar archives that only contain data and are not intended for execution/inclusion in PHP scripts. ### Parameters `filename` the full or relative path to the phar archive to open `alias` The alias that may be used to refer to the phar archive. Note that many phar archives specify an explicit alias inside the phar archive, and a [PharException](class.pharexception) will be thrown if a new alias is specified in this case. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions [PharException](class.pharexception) is thrown if an alias is passed in and the phar archive already has an explicit alias ### Examples **Example #1 A **Phar::loadPhar()** example** Phar::loadPhar can be used anywhere to load an external Phar archive, whereas Phar::mapPhar should be used in a loader stub for a Phar. ``` <?php try {     Phar::loadPhar('/path/to/phar.phar', 'my.phar');     echo file_get_contents('phar://my.phar/file.txt'); } catch (PharException $e) {     echo $e; } ?> ``` ### See Also * [Phar::mapPhar()](phar.mapphar) - Reads the currently executed file (a phar) and registers its manifest php IntlChar::getPropertyValueName IntlChar::getPropertyValueName ============================== (PHP 7, PHP 8) IntlChar::getPropertyValueName — Get the Unicode name for a property value ### Description ``` public static IntlChar::getPropertyValueName(int $property, int $value, int $type = IntlChar::LONG_PROPERTY_NAME): string|false ``` Returns the Unicode name for a given property value, as given in the Unicode database file PropertyValueAliases.txt. > > **Note**: > > > Some of the names in PropertyValueAliases.txt can only be retrieved using **`IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`**, not **`IntlChar::PROPERTY_GENERAL_CATEGORY`**. These include: > > > * "C" / "Other" > * "L" / "Letter" > * "LC" / "Cased\_Letter" > * "M" / "Mark" > * "N" / "Number" > * "P" / "Punctuation" > * "S" / "Symbol" > * "Z" / "Separator" > > ### Parameters `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). If out of range, or this method doesn't work with the given value, **`false`** is returned. `value` Selector for a value for the given property. If out of range, **`false`** is returned. In general, valid values range from `0` up to some maximum. There are a couple exceptions: * **`IntlChar::PROPERTY_BLOCK`** values begin at the non-zero value **`IntlChar::BLOCK_CODE_BASIC_LATIN`** * **`IntlChar::PROPERTY_CANONICAL_COMBINING_CLASS`** values are not contiguous and range from 0..240. `type` Selector for which name to get. If out of range, **`false`** is returned. All values have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to **`IntlChar::LONG_PROPERTY_NAME`**. ### Return Values Returns the name, or **`false`** if either the `property` or the `type` is out of range. Returns **`null`** on failure. If a given `type` returns **`false`**, then all larger values of `type` will return **`false`**, with one exception: if **`false`** is returned for **`IntlChar::SHORT_PROPERTY_NAME`**, then **`IntlChar::LONG_PROPERTY_NAME`** (and higher) may still return a non-**`false`** value. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK)); var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::SHORT_PROPERTY_NAME)); var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME)); var_dump(IntlChar::getPropertyValueName(IntlChar::PROPERTY_BLOCK, IntlChar::BLOCK_CODE_GREEK, IntlChar::LONG_PROPERTY_NAME + 1)); ?> ``` The above example will output: ``` string(16) "Greek_And_Coptic" string(5) "Greek" string(16) "Greek_And_Coptic" bool(false) ``` php SplStack::setIteratorMode SplStack::setIteratorMode ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplStack::setIteratorMode — Sets the mode of iteration ### Description ``` public SplStack::setIteratorMode(int $mode): void ``` ### Parameters `mode` There is only one iteration parameter you can modify. * The behavior of the iterator (either one or the other): + SplDoublyLinkedList::IT\_MODE\_DELETE (Elements are deleted by the iterator) + SplDoublyLinkedList::IT\_MODE\_KEEP (Elements are traversed by the iterator) The default mode is 0x2 : SplDoublyLinkedList::IT\_MODE\_LIFO | SplDoublyLinkedList::IT\_MODE\_KEEP **Warning** The direction of iteration can no longer be changed for SplStacks. Trying to do so will result in a [RuntimeException](class.runtimeexception) being thrown. ### Return Values No value is returned. php openal_buffer_data openal\_buffer\_data ==================== (PECL openal >= 0.1.0) openal\_buffer\_data — Load a buffer with data ### Description ``` openal_buffer_data( resource $buffer, int $format, string $data, int $freq ): bool ``` ### Parameters `buffer` An [Open AL(Buffer)](https://www.php.net/manual/en/openal.resources.php) resource (previously created by [openal\_buffer\_create()](function.openal-buffer-create)). `format` Format of `data`, one of: **`AL_FORMAT_MONO8`**, **`AL_FORMAT_MONO16`**, **`AL_FORMAT_STEREO8`** and **`AL_FORMAT_STEREO16`** `data` Block of binary audio data in the `format` and `freq` specified. `freq` Frequency of `data` given in Hz. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_buffer\_loadwav()](function.openal-buffer-loadwav) - Load a .wav file into a buffer * [openal\_stream()](function.openal-stream) - Begin streaming on a source php array_change_key_case array\_change\_key\_case ======================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) array\_change\_key\_case — Changes the case of all keys in an array ### Description ``` array_change_key_case(array $array, int $case = CASE_LOWER): array ``` Returns an array with all keys from `array` lowercased or uppercased. Numbered indices are left as is. ### Parameters `array` The array to work on `case` Either **`CASE_UPPER`** or **`CASE_LOWER`** (default) ### Return Values Returns an array with its keys lower or uppercased, or **`null`** if `array` is not an array. ### Examples **Example #1 **array\_change\_key\_case()** example** ``` <?php $input_array = array("FirSt" => 1, "SecOnd" => 4); print_r(array_change_key_case($input_array, CASE_UPPER)); ?> ``` The above example will output: ``` Array ( [FIRST] => 1 [SECOND] => 4 ) ``` ### Notes > > **Note**: > > > If an array has indices that will be the same once run through this function (e.g. "`keY`" and "`kEY`"), the value that is later in the array will override other indices. > >
programming_docs
php OAuthProvider::setRequestTokenPath OAuthProvider::setRequestTokenPath ================================== (PECL OAuth >= 1.0.0) OAuthProvider::setRequestTokenPath — Set request token path ### Description ``` final public OAuthProvider::setRequestTokenPath(string $path): bool ``` Sets the request tokens path. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `path` The path. ### Return Values **`true`** ### See Also * [OAuthProvider::tokenHandler()](oauthprovider.tokenhandler) - Set the tokenHandler handler callback php ldap_compare ldap\_compare ============= (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) ldap\_compare — Compare value of attribute found in entry specified with DN ### Description ``` ldap_compare( LDAP\Connection $ldap, string $dn, string $attribute, string $value, ?array $controls = null ): bool|int ``` Compare `value` of `attribute` with value of same attribute in an LDAP directory entry. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `dn` The distinguished name of an LDAP entity. `attribute` The attribute name. `value` The compared value. `controls` Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request. ### Return Values Returns **`true`** if `value` matches otherwise returns **`false`**. Returns -1 on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### Examples The following example demonstrates how to check whether or not given password matches the one defined in DN specified entry. **Example #1 Complete example of password check** ``` <?php $ds=ldap_connect("localhost");  // assuming the LDAP server is on this host if ($ds) {     // bind     if (ldap_bind($ds)) {         // prepare data         $dn = "cn=Matti Meikku, ou=My Unit, o=My Company, c=FI";         $value = "secretpassword";         $attr = "password";         // compare value         $r=ldap_compare($ds, $dn, $attr, $value);         if ($r === -1) {             echo "Error: " . ldap_error($ds);         } elseif ($r === true) {             echo "Password correct.";         } elseif ($r === false) {             echo "Wrong guess! Password incorrect.";         }     } else {         echo "Unable to bind to LDAP server.";     }     ldap_close($ds); } else {     echo "Unable to connect to LDAP server."; } ?> ``` ### Notes **Warning** **ldap\_compare()** can NOT be used to compare BINARY values! php DOMDocument::validate DOMDocument::validate ===================== (PHP 5, PHP 7, PHP 8) DOMDocument::validate — Validates the document based on its DTD ### Description ``` public DOMDocument::validate(): bool ``` Validates the document based on its DTD. You can also use the `validateOnParse` property of [DOMDocument](class.domdocument) to make a DTD validation. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. If the document has no DTD attached, this method will return **`false`**. ### Examples **Example #1 Example of DTD validation** ``` <?php $dom = new DOMDocument; $dom->load('book.xml'); if ($dom->validate()) {     echo "This document is valid!\n"; } ?> ``` You can also validate your XML file while loading it: ``` <?php $dom = new DOMDocument; $dom->validateOnParse = true; $dom->load('book.xml'); ?> ``` ### See Also * [DOMDocument::schemaValidate()](domdocument.schemavalidate) - Validates a document based on a schema. Only XML Schema 1.0 is supported. * [DOMDocument::schemaValidateSource()](domdocument.schemavalidatesource) - Validates a document based on a schema * [DOMDocument::relaxNGValidate()](domdocument.relaxngvalidate) - Performs relaxNG validation on the document * [DOMDocument::relaxNGValidateSource()](domdocument.relaxngvalidatesource) - Performs relaxNG validation on the document php The Imagick class The Imagick class ================= Class synopsis -------------- (PECL imagick 2, PECL imagick 3) class **Imagick** implements [Iterator](class.iterator) { public [\_\_construct](imagick.construct)([mixed](language.types.declarations#language.types.declarations.mixed) `$files` = ?) ``` public adaptiveBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public adaptiveResizeImage( int $columns, int $rows, bool $bestfit = false, bool $legacy = false ): bool ``` ``` public adaptiveSharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public adaptiveThresholdImage(int $width, int $height, int $offset): bool ``` ``` public addImage(Imagick $source): bool ``` ``` public addNoiseImage(int $noise_type, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public affineTransformImage(ImagickDraw $matrix): bool ``` ``` public animateImages(string $x_server): bool ``` ``` public annotateImage( ImagickDraw $draw_settings, float $x, float $y, float $angle, string $text ): bool ``` ``` public appendImages(bool $stack): Imagick ``` ``` public autoLevelImage(int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public averageImages(): Imagick ``` ``` public blackThresholdImage(mixed $threshold): bool ``` ``` public blueShiftImage(float $factor = 1.5): bool ``` ``` public blurImage(float $radius, float $sigma, int $channel = ?): bool ``` ``` public borderImage(mixed $bordercolor, int $width, int $height): bool ``` ``` public brightnessContrastImage(float $brightness, float $contrast, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public charcoalImage(float $radius, float $sigma): bool ``` ``` public chopImage( int $width, int $height, int $x, int $y ): bool ``` ``` public clampImage(int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public clear(): bool ``` ``` public clipImage(): bool ``` ``` public clipImagePath(string $pathname, string $inside): void ``` ``` public clipPathImage(string $pathname, bool $inside): bool ``` ``` public clone(): Imagick ``` ``` public clutImage(Imagick $lookup_table, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public coalesceImages(): Imagick ``` ``` public colorFloodfillImage( mixed $fill, float $fuzz, mixed $bordercolor, int $x, int $y ): bool ``` ``` public colorizeImage(mixed $colorize, mixed $opacity, bool $legacy = false): bool ``` ``` public colorMatrixImage(array $color_matrix = Imagick::CHANNEL_DEFAULT): bool ``` ``` public combineImages(int $channelType): Imagick ``` ``` public commentImage(string $comment): bool ``` ``` public compareImageChannels(Imagick $image, int $channelType, int $metricType): array ``` ``` public compareImageLayers(int $method): Imagick ``` ``` public compareImages(Imagick $compare, int $metric): array ``` ``` public compositeImage( Imagick $composite_object, int $composite, int $x, int $y, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public contrastImage(bool $sharpen): bool ``` ``` public contrastStretchImage(float $black_point, float $white_point, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public convolveImage(array $kernel, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public count(int $mode = 0): int ``` ``` public cropImage( int $width, int $height, int $x, int $y ): bool ``` ``` public cropThumbnailImage(int $width, int $height, bool $legacy = false): bool ``` ``` public current(): Imagick ``` ``` public cycleColormapImage(int $displace): bool ``` ``` public decipherImage(string $passphrase): bool ``` ``` public deconstructImages(): Imagick ``` ``` public deleteImageArtifact(string $artifact): bool ``` ``` public deleteImageProperty(string $name): bool ``` ``` public deskewImage(float $threshold): bool ``` ``` public despeckleImage(): bool ``` ``` public destroy(): bool ``` ``` public displayImage(string $servername): bool ``` ``` public displayImages(string $servername): bool ``` ``` public distortImage(int $method, array $arguments, bool $bestfit): bool ``` ``` public drawImage(ImagickDraw $draw): bool ``` ``` public edgeImage(float $radius): bool ``` ``` public embossImage(float $radius, float $sigma): bool ``` ``` public encipherImage(string $passphrase): bool ``` ``` public enhanceImage(): bool ``` ``` public equalizeImage(): bool ``` ``` public evaluateImage(int $op, float $constant, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public exportImagePixels( int $x, int $y, int $width, int $height, string $map, int $STORAGE ): array ``` ``` public extentImage( int $width, int $height, int $x, int $y ): bool ``` ``` public filter(ImagickKernel $ImagickKernel, int $channel = Imagick::CHANNEL_UNDEFINED): bool ``` ``` public flattenImages(): Imagick ``` ``` public flipImage(): bool ``` ``` public floodFillPaintImage( mixed $fill, float $fuzz, mixed $target, int $x, int $y, bool $invert, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public flopImage(): bool ``` ``` public forwardFourierTransformimage(bool $magnitude): bool ``` ``` public frameImage( mixed $matte_color, int $width, int $height, int $inner_bevel, int $outer_bevel ): bool ``` ``` public functionImage(int $function, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public fxImage(string $expression, int $channel = Imagick::CHANNEL_DEFAULT): Imagick ``` ``` public gammaImage(float $gamma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public gaussianBlurImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public getColorspace(): int ``` ``` public getCompression(): int ``` ``` public getCompressionQuality(): int ``` ``` public static getCopyright(): string ``` ``` public getFilename(): string ``` ``` public getFont(): string ``` ``` public getFormat(): string ``` ``` public getGravity(): int ``` ``` public static getHomeURL(): string ``` ``` public getImage(): Imagick ``` ``` public getImageAlphaChannel(): bool ``` ``` public getImageArtifact(string $artifact): string ``` ``` public getImageAttribute(string $key): string ``` ``` public getImageBackgroundColor(): ImagickPixel ``` ``` public getImageBlob(): string ``` ``` public getImageBluePrimary(): array ``` ``` public getImageBorderColor(): ImagickPixel ``` ``` public getImageChannelDepth(int $channel): int ``` ``` public getImageChannelDistortion(Imagick $reference, int $channel, int $metric): float ``` ``` public getImageChannelDistortions(Imagick $reference, int $metric, int $channel = Imagick::CHANNEL_DEFAULT): float ``` ``` public getImageChannelExtrema(int $channel): array ``` ``` public getImageChannelKurtosis(int $channel = Imagick::CHANNEL_DEFAULT): array ``` ``` public getImageChannelMean(int $channel): array ``` ``` public getImageChannelRange(int $channel): array ``` ``` public getImageChannelStatistics(): array ``` ``` public getImageClipMask(): Imagick ``` ``` public getImageColormapColor(int $index): ImagickPixel ``` ``` public getImageColors(): int ``` ``` public getImageColorspace(): int ``` ``` public getImageCompose(): int ``` ``` public getImageCompression(): int ``` ``` public getImageCompressionQuality(): int ``` ``` public getImageDelay(): int ``` ``` public getImageDepth(): int ``` ``` public getImageDispose(): int ``` ``` public getImageDistortion(MagickWand $reference, int $metric): float ``` ``` public getImageExtrema(): array ``` ``` public getImageFilename(): string ``` ``` public getImageFormat(): string ``` ``` public getImageGamma(): float ``` ``` public getImageGeometry(): array ``` ``` public getImageGravity(): int ``` ``` public getImageGreenPrimary(): array ``` ``` public getImageHeight(): int ``` ``` public getImageHistogram(): array ``` ``` public getImageIndex(): int ``` ``` public getImageInterlaceScheme(): int ``` ``` public getImageInterpolateMethod(): int ``` ``` public getImageIterations(): int ``` ``` public getImageLength(): int ``` ``` public getImageMatte(): bool ``` ``` public getImageMatteColor(): ImagickPixel ``` ``` public getImageMimeType(): string ``` ``` public getImageOrientation(): int ``` ``` public getImagePage(): array ``` ``` public getImagePixelColor(int $x, int $y): ImagickPixel ``` ``` public getImageProfile(string $name): string ``` ``` public getImageProfiles(string $pattern = "*", bool $include_values = true): array ``` ``` public getImageProperties(string $pattern = "*", bool $include_values = true): array ``` ``` public getImageProperty(string $name): string ``` ``` public getImageRedPrimary(): array ``` ``` public getImageRegion( int $width, int $height, int $x, int $y ): Imagick ``` ``` public getImageRenderingIntent(): int ``` ``` public getImageResolution(): array ``` ``` public getImagesBlob(): string ``` ``` public getImageScene(): int ``` ``` public getImageSignature(): string ``` ``` public getImageSize(): int ``` ``` public getImageTicksPerSecond(): int ``` ``` public getImageTotalInkDensity(): float ``` ``` public getImageType(): int ``` ``` public getImageUnits(): int ``` ``` public getImageVirtualPixelMethod(): int ``` ``` public getImageWhitePoint(): array ``` ``` public getImageWidth(): int ``` ``` public getInterlaceScheme(): int ``` ``` public getIteratorIndex(): int ``` ``` public getNumberImages(): int ``` ``` public getOption(string $key): string ``` ``` public static getPackageName(): string ``` ``` public getPage(): array ``` ``` public getPixelIterator(): ImagickPixelIterator ``` ``` public getPixelRegionIterator( int $x, int $y, int $columns, int $rows ): ImagickPixelIterator ``` ``` public getPointSize(): float ``` ``` public static getQuantum(): int ``` ``` public static getQuantumDepth(): array ``` ``` public static getQuantumRange(): array ``` ``` public static getRegistry(string $key): string ``` ``` public static getReleaseDate(): string ``` ``` public static getResource(int $type): int ``` ``` public static getResourceLimit(int $type): int ``` ``` public getSamplingFactors(): array ``` ``` public getSize(): array ``` ``` public getSizeOffset(): int ``` ``` public static getVersion(): array ``` ``` public haldClutImage(Imagick $clut, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public hasNextImage(): bool ``` ``` public hasPreviousImage(): bool ``` ``` public identifyFormat(string $embedText): string|false ``` ``` public identifyImage(bool $appendRawOutput = false): array ``` ``` public implodeImage(float $radius): bool ``` ``` public importImagePixels( int $x, int $y, int $width, int $height, string $map, int $storage, array $pixels ): bool ``` ``` public inverseFourierTransformImage(Imagick $complement, bool $magnitude): bool ``` ``` public labelImage(string $label): bool ``` ``` public levelImage( float $blackPoint, float $gamma, float $whitePoint, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public linearStretchImage(float $blackPoint, float $whitePoint): bool ``` ``` public liquidRescaleImage( int $width, int $height, float $delta_x, float $rigidity ): bool ``` ``` public static listRegistry(): array ``` ``` public magnifyImage(): bool ``` ``` public mapImage(Imagick $map, bool $dither): bool ``` ``` public matteFloodfillImage( float $alpha, float $fuzz, mixed $bordercolor, int $x, int $y ): bool ``` ``` public medianFilterImage(float $radius): bool ``` ``` public mergeImageLayers(int $layer_method): Imagick ``` ``` public minifyImage(): bool ``` ``` public modulateImage(float $brightness, float $saturation, float $hue): bool ``` ``` public montageImage( ImagickDraw $draw, string $tile_geometry, string $thumbnail_geometry, int $mode, string $frame ): Imagick ``` ``` public morphImages(int $number_frames): Imagick ``` ``` public morphology( int $morphologyMethod, int $iterations, ImagickKernel $ImagickKernel, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public mosaicImages(): Imagick ``` ``` public motionBlurImage( float $radius, float $sigma, float $angle, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public negateImage(bool $gray, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public newImage( int $cols, int $rows, mixed $background, string $format = ? ): bool ``` ``` public newPseudoImage(int $columns, int $rows, string $pseudoString): bool ``` ``` public nextImage(): bool ``` ``` public normalizeImage(int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public oilPaintImage(float $radius): bool ``` ``` public opaquePaintImage( mixed $target, mixed $fill, float $fuzz, bool $invert, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public optimizeImageLayers(): bool ``` ``` public orderedPosterizeImage(string $threshold_map, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public paintFloodfillImage( mixed $fill, float $fuzz, mixed $bordercolor, int $x, int $y, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public paintOpaqueImage( mixed $target, mixed $fill, float $fuzz, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public paintTransparentImage(mixed $target, float $alpha, float $fuzz): bool ``` ``` public pingImage(string $filename): bool ``` ``` public pingImageBlob(string $image): bool ``` ``` public pingImageFile(resource $filehandle, string $fileName = ?): bool ``` ``` public polaroidImage(ImagickDraw $properties, float $angle): bool ``` ``` public posterizeImage(int $levels, bool $dither): bool ``` ``` public previewImages(int $preview): bool ``` ``` public previousImage(): bool ``` ``` public profileImage(string $name, string $profile): bool ``` ``` public quantizeImage( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError ): bool ``` ``` public quantizeImages( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError ): bool ``` ``` public queryFontMetrics(ImagickDraw $properties, string $text, bool $multiline = ?): array ``` ``` public static queryFonts(string $pattern = "*"): array ``` ``` public static queryFormats(string $pattern = "*"): array ``` ``` public radialBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public raiseImage( int $width, int $height, int $x, int $y, bool $raise ): bool ``` ``` public randomThresholdImage(float $low, float $high, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public readImage(string $filename): bool ``` ``` public readImageBlob(string $image, string $filename = ?): bool ``` ``` public readImageFile(resource $filehandle, string $fileName = null): bool ``` ``` public readImages(array $filenames): bool ``` ``` public recolorImage(array $matrix): bool ``` ``` public reduceNoiseImage(float $radius): bool ``` ``` public remapImage(Imagick $replacement, int $DITHER): bool ``` ``` public removeImage(): bool ``` ``` public removeImageProfile(string $name): string ``` ``` public render(): bool ``` ``` public resampleImage( float $x_resolution, float $y_resolution, int $filter, float $blur ): bool ``` ``` public resetImagePage(string $page): bool ``` ``` public resizeImage( int $columns, int $rows, int $filter, float $blur, bool $bestfit = false, bool $legacy = false ): bool ``` ``` public rollImage(int $x, int $y): bool ``` ``` public rotateImage(mixed $background, float $degrees): bool ``` ``` public rotationalBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public roundCorners( float $x_rounding, float $y_rounding, float $stroke_width = 10, float $displace = 5, float $size_correction = -6 ): bool ``` ``` public sampleImage(int $columns, int $rows): bool ``` ``` public scaleImage( int $cols, int $rows, bool $bestfit = false, bool $legacy = false ): bool ``` ``` public segmentImage( int $COLORSPACE, float $cluster_threshold, float $smooth_threshold, bool $verbose = false ): bool ``` ``` public selectiveBlurImage( float $radius, float $sigma, float $threshold, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public separateImageChannel(int $channel): bool ``` ``` public sepiaToneImage(float $threshold): bool ``` ``` public setBackgroundColor(mixed $background): bool ``` ``` public setColorspace(int $COLORSPACE): bool ``` ``` public setCompression(int $compression): bool ``` ``` public setCompressionQuality(int $quality): bool ``` ``` public setFilename(string $filename): bool ``` ``` public setFirstIterator(): bool ``` ``` public setFont(string $font): bool ``` ``` public setFormat(string $format): bool ``` ``` public setGravity(int $gravity): bool ``` ``` public setImage(Imagick $replace): bool ``` ``` public setImageAlphaChannel(int $mode): bool ``` ``` public setImageArtifact(string $artifact, string $value): bool ``` ``` public setImageAttribute(string $key, string $value): bool ``` ``` public setImageBackgroundColor(mixed $background): bool ``` ``` public setImageBias(float $bias): bool ``` ``` public setImageBiasQuantum(string $bias): void ``` ``` public setImageBluePrimary(float $x, float $y): bool ``` ``` public setImageBorderColor(mixed $border): bool ``` ``` public setImageChannelDepth(int $channel, int $depth): bool ``` ``` public setImageClipMask(Imagick $clip_mask): bool ``` ``` public setImageColormapColor(int $index, ImagickPixel $color): bool ``` ``` public setImageColorspace(int $colorspace): bool ``` ``` public setImageCompose(int $compose): bool ``` ``` public setImageCompression(int $compression): bool ``` ``` public setImageCompressionQuality(int $quality): bool ``` ``` public setImageDelay(int $delay): bool ``` ``` public setImageDepth(int $depth): bool ``` ``` public setImageDispose(int $dispose): bool ``` ``` public setImageExtent(int $columns, int $rows): bool ``` ``` public setImageFilename(string $filename): bool ``` ``` public setImageFormat(string $format): bool ``` ``` public setImageGamma(float $gamma): bool ``` ``` public setImageGravity(int $gravity): bool ``` ``` public setImageGreenPrimary(float $x, float $y): bool ``` ``` public setImageIndex(int $index): bool ``` ``` public setImageInterlaceScheme(int $interlace_scheme): bool ``` ``` public setImageInterpolateMethod(int $method): bool ``` ``` public setImageIterations(int $iterations): bool ``` ``` public setImageMatte(bool $matte): bool ``` ``` public setImageMatteColor(mixed $matte): bool ``` ``` public setImageOpacity(float $opacity): bool ``` ``` public setImageOrientation(int $orientation): bool ``` ``` public setImagePage( int $width, int $height, int $x, int $y ): bool ``` ``` public setImageProfile(string $name, string $profile): bool ``` ``` public setImageProperty(string $name, string $value): bool ``` ``` public setImageRedPrimary(float $x, float $y): bool ``` ``` public setImageRenderingIntent(int $rendering_intent): bool ``` ``` public setImageResolution(float $x_resolution, float $y_resolution): bool ``` ``` public setImageScene(int $scene): bool ``` ``` public setImageTicksPerSecond(int $ticks_per_second): bool ``` ``` public setImageType(int $image_type): bool ``` ``` public setImageUnits(int $units): bool ``` ``` public setImageVirtualPixelMethod(int $method): bool ``` ``` public setImageWhitePoint(float $x, float $y): bool ``` ``` public setInterlaceScheme(int $interlace_scheme): bool ``` ``` public setIteratorIndex(int $index): bool ``` ``` public setLastIterator(): bool ``` ``` public setOption(string $key, string $value): bool ``` ``` public setPage( int $width, int $height, int $x, int $y ): bool ``` ``` public setPointSize(float $point_size): bool ``` ``` public setProgressMonitor(callable $callback): bool ``` ``` public static setRegistry(string $key, string $value): bool ``` ``` public setResolution(float $x_resolution, float $y_resolution): bool ``` ``` public static setResourceLimit(int $type, int $limit): bool ``` ``` public setSamplingFactors(array $factors): bool ``` ``` public setSize(int $columns, int $rows): bool ``` ``` public setSizeOffset(int $columns, int $rows, int $offset): bool ``` ``` public setType(int $image_type): bool ``` ``` public shadeImage(bool $gray, float $azimuth, float $elevation): bool ``` ``` public shadowImage( float $opacity, float $sigma, int $x, int $y ): bool ``` ``` public sharpenImage(float $radius, float $sigma, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public shaveImage(int $columns, int $rows): bool ``` ``` public shearImage(mixed $background, float $x_shear, float $y_shear): bool ``` ``` public sigmoidalContrastImage( bool $sharpen, float $alpha, float $beta, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public sketchImage(float $radius, float $sigma, float $angle): bool ``` ``` public smushImages(bool $stack, int $offset): Imagick ``` ``` public solarizeImage(int $threshold): bool ``` ``` public sparseColorImage(int $SPARSE_METHOD, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public spliceImage( int $width, int $height, int $x, int $y ): bool ``` ``` public spreadImage(float $radius): bool ``` ``` public statisticImage( int $type, int $width, int $height, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public steganoImage(Imagick $watermark_wand, int $offset): Imagick ``` ``` public stereoImage(Imagick $offset_wand): bool ``` ``` public stripImage(): bool ``` ``` public subImageMatch(Imagick $Imagick, array &$offset = ?, float &$similarity = ?): Imagick ``` ``` swirlImage(float $degrees): bool ``` ``` textureImage(Imagick $texture_wand): Imagick ``` ``` public thresholdImage(float $threshold, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` ``` public thumbnailImage( int $columns, int $rows, bool $bestfit = false, bool $fill = false, bool $legacy = false ): bool ``` ``` public tintImage(mixed $tint, mixed $opacity, bool $legacy = false): bool ``` ``` public __toString(): string ``` ``` public transformImage(string $crop, string $geometry): Imagick ``` ``` public transformImageColorspace(int $colorspace): bool ``` ``` public transparentPaintImage( mixed $target, float $alpha, float $fuzz, bool $invert ): bool ``` ``` public transposeImage(): bool ``` ``` public transverseImage(): bool ``` ``` public trimImage(float $fuzz): bool ``` ``` public uniqueImageColors(): bool ``` ``` public unsharpMaskImage( float $radius, float $sigma, float $amount, float $threshold, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` ``` public valid(): bool ``` ``` public vignetteImage( float $blackPoint, float $whitePoint, int $x, int $y ): bool ``` ``` public waveImage(float $amplitude, float $length): bool ``` ``` public whiteThresholdImage(mixed $threshold): bool ``` ``` public writeImage(string $filename = NULL): bool ``` ``` public writeImageFile(resource $filehandle, string $format = ?): bool ``` ``` public writeImages(string $filename, bool $adjoin): bool ``` ``` public writeImagesFile(resource $filehandle, string $format = ?): bool ``` } Image methods and global methods -------------------------------- The Imagick class has the ability to hold and operate on multiple images simultaneously. This is achieved through an internal stack. There is always an internal pointer that points at the current image. Some functions operate on all images in the Imagick class, but most operate only on the current image in the internal stack. As a convention, method names can contain the word Image to denote they affect only the current image in the stack. Class Methods ------------- Because there are so many methods, here is a handy list of methods, somewhat reduced to their general purpose: **Class methods by purpose**| Image effects | Get methods | Set methods | Read/write images | Other | | --- | --- | --- | --- | --- | | [Imagick::adaptiveBlurImage()](imagick.adaptiveblurimage) | [Imagick::getCompression()](imagick.getcompression) | [Imagick::setBackgroundColor()](imagick.setbackgroundcolor) | [Imagick::\_\_construct()](imagick.construct) | [Imagick::clear()](imagick.clear) | | [Imagick::adaptiveResizeImage()](imagick.adaptiveresizeimage) | [Imagick::getFilename()](imagick.getfilename) | [Imagick::setCompressionQuality()](imagick.setcompressionquality) | [Imagick::addImage()](imagick.addimage) | [Imagick::clone()](imagick.clone) | | [Imagick::adaptiveSharpenImage()](imagick.adaptivesharpenimage) | [Imagick::getFormat()](imagick.getformat) | [Imagick::setCompression()](imagick.setcompression) | [Imagick::appendImages()](imagick.appendimages) | [Imagick::current()](imagick.current) | | [Imagick::adaptiveThresholdImage()](imagick.adaptivethresholdimage) | [Imagick::getImageBackgroundColor()](imagick.getimagebackgroundcolor) | [Imagick::setFilename()](imagick.setfilename) | [Imagick::getFilename()](imagick.getfilename) | [Imagick::destroy()](imagick.destroy) | | [Imagick::addNoiseImage()](imagick.addnoiseimage) | [Imagick::getImageBlob()](imagick.getimageblob) | [Imagick::getImagesBlob()](imagick.getimagesblob) | [Imagick::setFormat()](imagick.setformat) | [Imagick::getFormat()](imagick.getformat) | | [Imagick::affinetransformimage()](imagick.affinetransformimage) | [Imagick::getImageBluePrimary()](imagick.getimageblueprimary) | [Imagick::setImageBackgroundColor()](imagick.setimagebackgroundcolor) | [Imagick::getImageFilename()](imagick.getimagefilename) | [Imagick::getHomeURL()](imagick.gethomeurl) | | [Imagick::annotateImage()](imagick.annotateimage) | [Imagick::getImageBorderColor()](imagick.getimagebordercolor) | [Imagick::setFirstIterator()](imagick.setfirstiterator) | [Imagick::getImageFormat()](imagick.getimageformat) | [Imagick::commentImage()](imagick.commentimage) | | [Imagick::averageImages()](imagick.averageimages) | [Imagick::getImageChannelDepth()](imagick.getimagechanneldepth) | [Imagick::setImageBias()](imagick.setimagebias) | [Imagick::getImage()](imagick.getimage) | [Imagick::getNumberImages()](imagick.getnumberimages) | | [Imagick::blackThresholdImage()](imagick.blackthresholdimage) | [Imagick::getImageChannelDistortion()](imagick.getimagechanneldistortion) | [Imagick::setImageBluePrimary()](imagick.setimageblueprimary) | [Imagick::setImageFilename()](imagick.setimagefilename) | [Imagick::getReleaseDate()](imagick.getreleasedate) | | [Imagick::blurImage()](imagick.blurimage) | [Imagick::getImageChannelExtrema()](imagick.getimagechannelextrema) | [Imagick::setImageBorderColor()](imagick.setimagebordercolor) | [Imagick::setImageFormat()](imagick.setimageformat) | [Imagick::getVersion()](imagick.getversion) | | [Imagick::borderImage()](imagick.borderimage) | [Imagick::getImageChannelMean()](imagick.getimagechannelmean) | [Imagick::setImageChannelDepth()](imagick.setimagechanneldepth) | [Imagick::readImageFile()](imagick.readimagefile) | [Imagick::hasNextImage()](imagick.hasnextimage) | | [Imagick::charcoalImage()](imagick.charcoalimage) | [Imagick::getImageChannelStatistics()](imagick.getimagechannelstatistics) | [Imagick::setImageColormapColor()](imagick.setimagecolormapcolor) | [Imagick::readImage()](imagick.readimage) | [Imagick::hasPreviousImage()](imagick.haspreviousimage) | | [Imagick::chopImage()](imagick.chopimage) | [Imagick::getImageColormapColor()](imagick.getimagecolormapcolor) | [Imagick::setImageColorSpace()](imagick.setimagecolorspace) | [Imagick::writeImages()](imagick.writeimages) | [Imagick::labelImage()](imagick.labelimage) | | [Imagick::clipImage()](imagick.clipimage) | [Imagick::getImageColorspace()](imagick.getimagecolorspace) | [Imagick::setImageCompose()](imagick.setimagecompose) | [Imagick::writeImage()](imagick.writeimage) | [Imagick::newImage()](imagick.newimage) | | [Imagick::clipPathImage()](imagick.clippathimage) | [Imagick::getImageColors()](imagick.getimagecolors) | [Imagick::setImageCompression()](imagick.setimagecompression) | | [Imagick::newPseudoImage()](imagick.newpseudoimage) | | [Imagick::coalesceImages()](imagick.coalesceimages) | [Imagick::getImageCompose()](imagick.getimagecompose) | [Imagick::setImageDelay()](imagick.setimagedelay) | | [Imagick::nextImage()](imagick.nextimage) | | [Imagick::colorFloodFillImage()](imagick.colorfloodfillimage) | [Imagick::getImageDelay()](imagick.getimagedelay) | [Imagick::setImageDepth()](imagick.setimagedepth) | | [Imagick::pingImageBlob()](imagick.pingimageblob) | | [Imagick::colorizeImage()](imagick.colorizeimage) | [Imagick::getImageDepth()](imagick.getimagedepth) | [Imagick::setImageDispose()](imagick.setimagedispose) | | [Imagick::pingImageFile()](imagick.pingimagefile) | | [Imagick::combineImages()](imagick.combineimages) | [Imagick::getImageDispose()](imagick.getimagedispose) | [Imagick::setImageDispose()](imagick.setimagedispose) | | [Imagick::pingImage()](imagick.pingimage) | | [Imagick::compareImageChannels()](imagick.compareimagechannels) | [Imagick::getImageDistortion()](imagick.getimagedistortion) | [Imagick::setImageExtent()](imagick.setimageextent) | | [Imagick::previousImage()](imagick.previousimage) | | [Imagick::compareImageLayers()](imagick.compareimagelayers) | [Imagick::getImageExtrema()](imagick.getimageextrema) | [Imagick::setImageFilename()](imagick.setimagefilename) | | [Imagick::profileImage()](imagick.profileimage) | | [Imagick::compositeImage()](imagick.compositeimage) | [Imagick::getImageFilename()](imagick.getimagefilename) | [Imagick::setImageFormat()](imagick.setimageformat) | | [Imagick::queryFormats()](imagick.queryformats) | | [Imagick::contrastImage()](imagick.contrastimage) | [Imagick::getImageFormat()](imagick.getimageformat) | [Imagick::setImageGamma()](imagick.setimagegamma) | | [Imagick::removeImageProfile()](imagick.removeimageprofile) | | [Imagick::contrastStretchImage()](imagick.contraststretchimage) | [Imagick::getImageGamma()](imagick.getimagegamma) | [Imagick::setImageGreenPrimary()](imagick.setimagegreenprimary) | | [Imagick::removeImage()](imagick.removeimage) | | [Imagick::convolveImage()](imagick.convolveimage) | [Imagick::getImageGeometry()](imagick.getimagegeometry) | [Imagick::setImageIndex()](imagick.setimageindex) | | [Imagick::setFirstIterator()](imagick.setfirstiterator) | | [Imagick::cropImage()](imagick.cropimage) | [Imagick::getImageGreenPrimary()](imagick.getimagegreenprimary) | [Imagick::setImageInterpolateMethod()](imagick.setimageinterpolatemethod) | | [Imagick::setImageIndex()](imagick.setimageindex) | | [Imagick::cycleColormapImage()](imagick.cyclecolormapimage) | [Imagick::getImageHeight()](imagick.getimageheight) | [Imagick::setImageIterations()](imagick.setimageiterations) | | [Imagick::valid()](imagick.valid) | | [Imagick::deconstructImages()](imagick.deconstructimages) | [Imagick::getImageHistogram()](imagick.getimagehistogram) | [Imagick::setImageMatteColor()](imagick.setimagemattecolor) | | [Imagick::getCopyright()](imagick.getcopyright) | | [Imagick::drawImage()](imagick.drawimage) | [Imagick::getImageIndex()](imagick.getimageindex) | [Imagick::setImageMatte()](imagick.setimagematte) | | | | [Imagick::edgeImage()](imagick.edgeimage) | [Imagick::getImageInterlaceScheme()](imagick.getimageinterlacescheme) | [Imagick::setImagePage()](imagick.setimagepage) | | | | [Imagick::embossImage()](imagick.embossimage) | [Imagick::getImageInterpolateMethod()](imagick.getimageinterpolatemethod) | [Imagick::setImageProfile()](imagick.setimageprofile) | | | | [Imagick::enhanceImage()](imagick.enhanceimage) | [Imagick::getImageIterations()](imagick.getimageiterations) | [Imagick::setImageProperty()](imagick.setimageproperty) | | | | [Imagick::equalizeImage()](imagick.equalizeimage) | [Imagick::getImageMatteColor()](imagick.getimagemattecolor) | [Imagick::setImageRedPrimary()](imagick.setimageredprimary) | | | | [Imagick::evaluateImage()](imagick.evaluateimage) | [Imagick::getImageMatte()](imagick.getimagematte) | [Imagick::setImageRenderingIntent()](imagick.setimagerenderingintent) | | | | [Imagick::flattenImages()](imagick.flattenimages) | [Imagick::getImagePage()](imagick.getimagepage) | [Imagick::setImageResolution()](imagick.setimageresolution) | | | | [Imagick::flipImage()](imagick.flipimage) | [Imagick::getImagePixelColor()](imagick.getimagepixelcolor) | [Imagick::setImageScene()](imagick.setimagescene) | | | | [Imagick::flopImage()](imagick.flopimage) | [Imagick::getImageProfile()](imagick.getimageprofile) | [Imagick::setImageTicksPerSecond()](imagick.setimagetickspersecond) | | | | | [Imagick::getImageProperty()](imagick.getimageproperty) | [Imagick::setImageType()](imagick.setimagetype) | | | | [Imagick::fxImage()](imagick.fximage) | [Imagick::getImageRedPrimary()](imagick.getimageredprimary) | [Imagick::setImageUnits()](imagick.setimageunits) | | | | [Imagick::gammaImage()](imagick.gammaimage) | [Imagick::getImageRegion()](imagick.getimageregion) | [Imagick::setImageVirtualPixelMethod()](imagick.setimagevirtualpixelmethod) | | | | [Imagick::gaussianBlurImage()](imagick.gaussianblurimage) | [Imagick::getImageRenderingIntent()](imagick.getimagerenderingintent) | [Imagick::setImageWhitepoint()](imagick.setimagewhitepoint) | | | | [Imagick::implodeImage()](imagick.implodeimage) | [Imagick::getImageResolution()](imagick.getimageresolution) | [Imagick::setInterlaceScheme()](imagick.setinterlacescheme) | | | | [Imagick::levelImage()](imagick.levelimage) | [Imagick::getImageScene()](imagick.getimagescene) | [Imagick::setOption()](imagick.setoption) | | | | [Imagick::linearStretchImage()](imagick.linearstretchimage) | [Imagick::getImageSignature()](imagick.getimagesignature) | [Imagick::setPage()](imagick.setpage) | | | | [Imagick::magnifyImage()](imagick.magnifyimage) | [Imagick::getImageTicksPerSecond()](imagick.getimagetickspersecond) | [Imagick::setResolution()](imagick.setresolution) | | | | [Imagick::matteFloodFillImage()](imagick.mattefloodfillimage) | [Imagick::getImageTotalInkDensity()](imagick.getimagetotalinkdensity) | [Imagick::setResourceLimit()](imagick.setresourcelimit) | | | | [Imagick::medianFilterImage()](imagick.medianfilterimage) | [Imagick::getImageType()](imagick.getimagetype) | [Imagick::setSamplingFactors()](imagick.setsamplingfactors) | | | | [Imagick::minifyImage()](imagick.minifyimage) | [Imagick::getImageUnits()](imagick.getimageunits) | [Imagick::setSizeOffset()](imagick.setsizeoffset) | | | | [Imagick::modulateImage()](imagick.modulateimage) | [Imagick::getImageVirtualPixelMethod()](imagick.getimagevirtualpixelmethod) | [Imagick::setSize()](imagick.setsize) | | | | [Imagick::montageImage()](imagick.montageimage) | [Imagick::getImageWhitepoint()](imagick.getimagewhitepoint) | [Imagick::setType()](imagick.settype) | | | | [Imagick::morphImages()](imagick.morphimages) | [Imagick::getImageWidth()](imagick.getimagewidth) | | | | | [Imagick::mosaicImages()](imagick.mosaicimages) | [Imagick::getImage()](imagick.getimage) | | | | | [Imagick::motionBlurImage()](imagick.motionblurimage) | [Imagick::getInterlaceScheme()](imagick.getinterlacescheme) | | | | | [Imagick::negateImage()](imagick.negateimage) | [Imagick::getNumberImages()](imagick.getnumberimages) | | | | | [Imagick::normalizeImage()](imagick.normalizeimage) | [Imagick::getOption()](imagick.getoption) | | | | | [Imagick::oilPaintImage()](imagick.oilpaintimage) | [Imagick::getPackageName()](imagick.getpackagename) | | | | | [Imagick::optimizeImageLayers()](imagick.optimizeimagelayers) | [Imagick::getPage()](imagick.getpage) | | | | | [Imagick::paintOpaqueImage()](imagick.paintopaqueimage) | [Imagick::getPixelIterator()](imagick.getpixeliterator) | | | | | [Imagick::paintTransparentImage()](imagick.painttransparentimage) | [Imagick::getPixelRegionIterator()](imagick.getpixelregioniterator) | | | | | [Imagick::posterizeImage()](imagick.posterizeimage) | [Imagick::getQuantumDepth()](imagick.getquantumdepth) | | | | | [Imagick::radialBlurImage()](imagick.radialblurimage) | [Imagick::getQuantumRange()](imagick.getquantumrange) | | | | | [Imagick::raiseImage()](imagick.raiseimage) | [Imagick::getResourceLimit()](imagick.getresourcelimit) | | | | | [Imagick::randomThresholdImage()](imagick.randomthresholdimage) | [Imagick::getResource()](imagick.getresource) | | | | | [Imagick::reduceNoiseImage()](imagick.reducenoiseimage) | [Imagick::getSamplingFactors()](imagick.getsamplingfactors) | | | | | [Imagick::render()](imagick.render) | [Imagick::getSizeOffset()](imagick.getsizeoffset) | | | | | [Imagick::resampleImage()](imagick.resampleimage) | [Imagick::getSize()](imagick.getsize) | | | | | [Imagick::resizeImage()](imagick.resizeimage) | [Imagick::identifyImage()](imagick.identifyimage) | | | | | [Imagick::rollImage()](imagick.rollimage) | [Imagick::getImageSize()](imagick.getimagesize) | | | | | [Imagick::rotateImage()](imagick.rotateimage) | | | | | | [Imagick::sampleImage()](imagick.sampleimage) | | | | | | [Imagick::scaleImage()](imagick.scaleimage) | | | | | | [Imagick::separateImageChannel()](imagick.separateimagechannel) | | | | | | [Imagick::sepiaToneImage()](imagick.sepiatoneimage) | | | | | | [Imagick::shadeImage()](imagick.shadeimage) | | | | | | [Imagick::shadowImage()](imagick.shadowimage) | | | | | | [Imagick::sharpenImage()](imagick.sharpenimage) | | | | | | [Imagick::shaveImage()](imagick.shaveimage) | | | | | | [Imagick::shearImage()](imagick.shearimage) | | | | | | [Imagick::sigmoidalContrastImage()](imagick.sigmoidalcontrastimage) | | | | | | [Imagick::sketchImage()](imagick.sketchimage) | | | | | | [Imagick::solarizeImage()](imagick.solarizeimage) | | | | | | [Imagick::spliceImage()](imagick.spliceimage) | | | | | | [Imagick::spreadImage()](imagick.spreadimage) | | | | | | [Imagick::steganoImage()](imagick.steganoimage) | | | | | | [Imagick::stereoImage()](imagick.stereoimage) | | | | | | [Imagick::stripImage()](imagick.stripimage) | | | | | | [Imagick::swirlImage()](imagick.swirlimage) | | | | | | [Imagick::textureImage()](imagick.textureimage) | | | | | | [Imagick::thresholdImage()](imagick.thresholdimage) | | | | | | [Imagick::thumbnailImage()](imagick.thumbnailimage) | | | | | | [Imagick::tintImage()](imagick.tintimage) | | | | | | [Imagick::transverseImage()](imagick.transverseimage) | | | | | | [Imagick::trimImage()](imagick.trimimage) | | | | | | [Imagick::uniqueImageColors()](imagick.uniqueimagecolors) | | | | | | [Imagick::unsharpMaskImage()](imagick.unsharpmaskimage) | | | | | | [Imagick::vignetteImage()](imagick.vignetteimage) | | | | | | [Imagick::waveImage()](imagick.waveimage) | | | | | | [Imagick::whiteThresholdImage()](imagick.whitethresholdimage) | | | | | Table of Contents ----------------- * [Imagick::adaptiveBlurImage](imagick.adaptiveblurimage) — Adds adaptive blur filter to image * [Imagick::adaptiveResizeImage](imagick.adaptiveresizeimage) — Adaptively resize image with data dependent triangulation * [Imagick::adaptiveSharpenImage](imagick.adaptivesharpenimage) — Adaptively sharpen the image * [Imagick::adaptiveThresholdImage](imagick.adaptivethresholdimage) — Selects a threshold for each pixel based on a range of intensity * [Imagick::addImage](imagick.addimage) — Adds new image to Imagick object image list * [Imagick::addNoiseImage](imagick.addnoiseimage) — Adds random noise to the image * [Imagick::affineTransformImage](imagick.affinetransformimage) — Transforms an image * [Imagick::animateImages](imagick.animateimages) — Animates an image or images * [Imagick::annotateImage](imagick.annotateimage) — Annotates an image with text * [Imagick::appendImages](imagick.appendimages) — Append a set of images * [Imagick::autoLevelImage](imagick.autolevelimage) — Description * [Imagick::averageImages](imagick.averageimages) — Average a set of images * [Imagick::blackThresholdImage](imagick.blackthresholdimage) — Forces all pixels below the threshold into black * [Imagick::blueShiftImage](imagick.blueshiftimage) — Description * [Imagick::blurImage](imagick.blurimage) — Adds blur filter to image * [Imagick::borderImage](imagick.borderimage) — Surrounds the image with a border * [Imagick::brightnessContrastImage](imagick.brightnesscontrastimage) — Description * [Imagick::charcoalImage](imagick.charcoalimage) — Simulates a charcoal drawing * [Imagick::chopImage](imagick.chopimage) — Removes a region of an image and trims * [Imagick::clampImage](imagick.clampimage) — Description * [Imagick::clear](imagick.clear) — Clears all resources associated to Imagick object * [Imagick::clipImage](imagick.clipimage) — Clips along the first path from the 8BIM profile * [Imagick::clipImagePath](imagick.clipimagepath) — Description * [Imagick::clipPathImage](imagick.clippathimage) — Clips along the named paths from the 8BIM profile * [Imagick::clone](imagick.clone) — Makes an exact copy of the Imagick object * [Imagick::clutImage](imagick.clutimage) — Replaces colors in the image * [Imagick::coalesceImages](imagick.coalesceimages) — Composites a set of images * [Imagick::colorFloodfillImage](imagick.colorfloodfillimage) — Changes the color value of any pixel that matches target * [Imagick::colorizeImage](imagick.colorizeimage) — Blends the fill color with the image * [Imagick::colorMatrixImage](imagick.colormatriximage) — Description * [Imagick::combineImages](imagick.combineimages) — Combines one or more images into a single image * [Imagick::commentImage](imagick.commentimage) — Adds a comment to your image * [Imagick::compareImageChannels](imagick.compareimagechannels) — Returns the difference in one or more images * [Imagick::compareImageLayers](imagick.compareimagelayers) — Returns the maximum bounding region between images * [Imagick::compareImages](imagick.compareimages) — Compares an image to a reconstructed image * [Imagick::compositeImage](imagick.compositeimage) — Composite one image onto another * [Imagick::\_\_construct](imagick.construct) — The Imagick constructor * [Imagick::contrastImage](imagick.contrastimage) — Change the contrast of the image * [Imagick::contrastStretchImage](imagick.contraststretchimage) — Enhances the contrast of a color image * [Imagick::convolveImage](imagick.convolveimage) — Applies a custom convolution kernel to the image * [Imagick::count](imagick.count) — Get the number of images * [Imagick::cropImage](imagick.cropimage) — Extracts a region of the image * [Imagick::cropThumbnailImage](imagick.cropthumbnailimage) — Creates a crop thumbnail * [Imagick::current](imagick.current) — Returns a reference to the current Imagick object * [Imagick::cycleColormapImage](imagick.cyclecolormapimage) — Displaces an image's colormap * [Imagick::decipherImage](imagick.decipherimage) — Deciphers an image * [Imagick::deconstructImages](imagick.deconstructimages) — Returns certain pixel differences between images * [Imagick::deleteImageArtifact](imagick.deleteimageartifact) — Delete image artifact * [Imagick::deleteImageProperty](imagick.deleteimageproperty) — Description * [Imagick::deskewImage](imagick.deskewimage) — Removes skew from the image * [Imagick::despeckleImage](imagick.despeckleimage) — Reduces the speckle noise in an image * [Imagick::destroy](imagick.destroy) — Destroys the Imagick object * [Imagick::displayImage](imagick.displayimage) — Displays an image * [Imagick::displayImages](imagick.displayimages) — Displays an image or image sequence * [Imagick::distortImage](imagick.distortimage) — Distorts an image using various distortion methods * [Imagick::drawImage](imagick.drawimage) — Renders the ImagickDraw object on the current image * [Imagick::edgeImage](imagick.edgeimage) — Enhance edges within the image * [Imagick::embossImage](imagick.embossimage) — Returns a grayscale image with a three-dimensional effect * [Imagick::encipherImage](imagick.encipherimage) — Enciphers an image * [Imagick::enhanceImage](imagick.enhanceimage) — Improves the quality of a noisy image * [Imagick::equalizeImage](imagick.equalizeimage) — Equalizes the image histogram * [Imagick::evaluateImage](imagick.evaluateimage) — Applies an expression to an image * [Imagick::exportImagePixels](imagick.exportimagepixels) — Exports raw image pixels * [Imagick::extentImage](imagick.extentimage) — Set image size * [Imagick::filter](imagick.filter) — Description * [Imagick::flattenImages](imagick.flattenimages) — Merges a sequence of images * [Imagick::flipImage](imagick.flipimage) — Creates a vertical mirror image * [Imagick::floodFillPaintImage](imagick.floodfillpaintimage) — Changes the color value of any pixel that matches target * [Imagick::flopImage](imagick.flopimage) — Creates a horizontal mirror image * [Imagick::forwardFourierTransformImage](imagick.forwardfouriertransformimage) — Description * [Imagick::frameImage](imagick.frameimage) — Adds a simulated three-dimensional border * [Imagick::functionImage](imagick.functionimage) — Applies a function on the image * [Imagick::fxImage](imagick.fximage) — Evaluate expression for each pixel in the image * [Imagick::gammaImage](imagick.gammaimage) — Gamma-corrects an image * [Imagick::gaussianBlurImage](imagick.gaussianblurimage) — Blurs an image * [Imagick::getColorspace](imagick.getcolorspace) — Gets the colorspace * [Imagick::getCompression](imagick.getcompression) — Gets the object compression type * [Imagick::getCompressionQuality](imagick.getcompressionquality) — Gets the object compression quality * [Imagick::getCopyright](imagick.getcopyright) — Returns the ImageMagick API copyright as a string * [Imagick::getFilename](imagick.getfilename) — The filename associated with an image sequence * [Imagick::getFont](imagick.getfont) — Gets font * [Imagick::getFormat](imagick.getformat) — Returns the format of the Imagick object * [Imagick::getGravity](imagick.getgravity) — Gets the gravity * [Imagick::getHomeURL](imagick.gethomeurl) — Returns the ImageMagick home URL * [Imagick::getImage](imagick.getimage) — Returns a new Imagick object * [Imagick::getImageAlphaChannel](imagick.getimagealphachannel) — Checks if the image has an alpha channel * [Imagick::getImageArtifact](imagick.getimageartifact) — Get image artifact * [Imagick::getImageAttribute](imagick.getimageattribute) — Returns a named attribute * [Imagick::getImageBackgroundColor](imagick.getimagebackgroundcolor) — Returns the image background color * [Imagick::getImageBlob](imagick.getimageblob) — Returns the image sequence as a blob * [Imagick::getImageBluePrimary](imagick.getimageblueprimary) — Returns the chromaticy blue primary point * [Imagick::getImageBorderColor](imagick.getimagebordercolor) — Returns the image border color * [Imagick::getImageChannelDepth](imagick.getimagechanneldepth) — Gets the depth for a particular image channel * [Imagick::getImageChannelDistortion](imagick.getimagechanneldistortion) — Compares image channels of an image to a reconstructed image * [Imagick::getImageChannelDistortions](imagick.getimagechanneldistortions) — Gets channel distortions * [Imagick::getImageChannelExtrema](imagick.getimagechannelextrema) — Gets the extrema for one or more image channels * [Imagick::getImageChannelKurtosis](imagick.getimagechannelkurtosis) — The getImageChannelKurtosis purpose * [Imagick::getImageChannelMean](imagick.getimagechannelmean) — Gets the mean and standard deviation * [Imagick::getImageChannelRange](imagick.getimagechannelrange) — Gets channel range * [Imagick::getImageChannelStatistics](imagick.getimagechannelstatistics) — Returns statistics for each channel in the image * [Imagick::getImageClipMask](imagick.getimageclipmask) — Gets image clip mask * [Imagick::getImageColormapColor](imagick.getimagecolormapcolor) — Returns the color of the specified colormap index * [Imagick::getImageColors](imagick.getimagecolors) — Gets the number of unique colors in the image * [Imagick::getImageColorspace](imagick.getimagecolorspace) — Gets the image colorspace * [Imagick::getImageCompose](imagick.getimagecompose) — Returns the composite operator associated with the image * [Imagick::getImageCompression](imagick.getimagecompression) — Gets the current image's compression type * [Imagick::getImageCompressionQuality](imagick.getimagecompressionquality) — Gets the current image's compression quality * [Imagick::getImageDelay](imagick.getimagedelay) — Gets the image delay * [Imagick::getImageDepth](imagick.getimagedepth) — Gets the image depth * [Imagick::getImageDispose](imagick.getimagedispose) — Gets the image disposal method * [Imagick::getImageDistortion](imagick.getimagedistortion) — Compares an image to a reconstructed image * [Imagick::getImageExtrema](imagick.getimageextrema) — Gets the extrema for the image * [Imagick::getImageFilename](imagick.getimagefilename) — Returns the filename of a particular image in a sequence * [Imagick::getImageFormat](imagick.getimageformat) — Returns the format of a particular image in a sequence * [Imagick::getImageGamma](imagick.getimagegamma) — Gets the image gamma * [Imagick::getImageGeometry](imagick.getimagegeometry) — Gets the width and height as an associative array * [Imagick::getImageGravity](imagick.getimagegravity) — Gets the image gravity * [Imagick::getImageGreenPrimary](imagick.getimagegreenprimary) — Returns the chromaticy green primary point * [Imagick::getImageHeight](imagick.getimageheight) — Returns the image height * [Imagick::getImageHistogram](imagick.getimagehistogram) — Gets the image histogram * [Imagick::getImageIndex](imagick.getimageindex) — Gets the index of the current active image * [Imagick::getImageInterlaceScheme](imagick.getimageinterlacescheme) — Gets the image interlace scheme * [Imagick::getImageInterpolateMethod](imagick.getimageinterpolatemethod) — Returns the interpolation method * [Imagick::getImageIterations](imagick.getimageiterations) — Gets the image iterations * [Imagick::getImageLength](imagick.getimagelength) — Returns the image length in bytes * [Imagick::getImageMatte](imagick.getimagematte) — Return if the image has a matte channel * [Imagick::getImageMatteColor](imagick.getimagemattecolor) — Returns the image matte color * [Imagick::getImageMimeType](imagick.getimagemimetype) — Description * [Imagick::getImageOrientation](imagick.getimageorientation) — Gets the image orientation * [Imagick::getImagePage](imagick.getimagepage) — Returns the page geometry * [Imagick::getImagePixelColor](imagick.getimagepixelcolor) — Returns the color of the specified pixel * [Imagick::getImageProfile](imagick.getimageprofile) — Returns the named image profile * [Imagick::getImageProfiles](imagick.getimageprofiles) — Returns the image profiles * [Imagick::getImageProperties](imagick.getimageproperties) — Returns the image properties * [Imagick::getImageProperty](imagick.getimageproperty) — Returns the named image property * [Imagick::getImageRedPrimary](imagick.getimageredprimary) — Returns the chromaticity red primary point * [Imagick::getImageRegion](imagick.getimageregion) — Extracts a region of the image * [Imagick::getImageRenderingIntent](imagick.getimagerenderingintent) — Gets the image rendering intent * [Imagick::getImageResolution](imagick.getimageresolution) — Gets the image X and Y resolution * [Imagick::getImagesBlob](imagick.getimagesblob) — Returns all image sequences as a blob * [Imagick::getImageScene](imagick.getimagescene) — Gets the image scene * [Imagick::getImageSignature](imagick.getimagesignature) — Generates an SHA-256 message digest * [Imagick::getImageSize](imagick.getimagesize) — Returns the image length in bytes * [Imagick::getImageTicksPerSecond](imagick.getimagetickspersecond) — Gets the image ticks-per-second * [Imagick::getImageTotalInkDensity](imagick.getimagetotalinkdensity) — Gets the image total ink density * [Imagick::getImageType](imagick.getimagetype) — Gets the potential image type * [Imagick::getImageUnits](imagick.getimageunits) — Gets the image units of resolution * [Imagick::getImageVirtualPixelMethod](imagick.getimagevirtualpixelmethod) — Returns the virtual pixel method * [Imagick::getImageWhitePoint](imagick.getimagewhitepoint) — Returns the chromaticity white point * [Imagick::getImageWidth](imagick.getimagewidth) — Returns the image width * [Imagick::getInterlaceScheme](imagick.getinterlacescheme) — Gets the object interlace scheme * [Imagick::getIteratorIndex](imagick.getiteratorindex) — Gets the index of the current active image * [Imagick::getNumberImages](imagick.getnumberimages) — Returns the number of images in the object * [Imagick::getOption](imagick.getoption) — Returns a value associated with the specified key * [Imagick::getPackageName](imagick.getpackagename) — Returns the ImageMagick package name * [Imagick::getPage](imagick.getpage) — Returns the page geometry * [Imagick::getPixelIterator](imagick.getpixeliterator) — Returns a MagickPixelIterator * [Imagick::getPixelRegionIterator](imagick.getpixelregioniterator) — Get an ImagickPixelIterator for an image section * [Imagick::getPointSize](imagick.getpointsize) — Gets point size * [Imagick::getQuantum](imagick.getquantum) — Description * [Imagick::getQuantumDepth](imagick.getquantumdepth) — Gets the quantum depth * [Imagick::getQuantumRange](imagick.getquantumrange) — Returns the Imagick quantum range * [Imagick::getRegistry](imagick.getregistry) — Description * [Imagick::getReleaseDate](imagick.getreleasedate) — Returns the ImageMagick release date * [Imagick::getResource](imagick.getresource) — Returns the specified resource's memory usage * [Imagick::getResourceLimit](imagick.getresourcelimit) — Returns the specified resource limit * [Imagick::getSamplingFactors](imagick.getsamplingfactors) — Gets the horizontal and vertical sampling factor * [Imagick::getSize](imagick.getsize) — Returns the size associated with the Imagick object * [Imagick::getSizeOffset](imagick.getsizeoffset) — Returns the size offset * [Imagick::getVersion](imagick.getversion) — Returns the ImageMagick API version * [Imagick::haldClutImage](imagick.haldclutimage) — Replaces colors in the image * [Imagick::hasNextImage](imagick.hasnextimage) — Checks if the object has more images * [Imagick::hasPreviousImage](imagick.haspreviousimage) — Checks if the object has a previous image * [Imagick::identifyFormat](imagick.identifyformat) — Description * [Imagick::identifyImage](imagick.identifyimage) — Identifies an image and fetches attributes * [Imagick::implodeImage](imagick.implodeimage) — Creates a new image as a copy * [Imagick::importImagePixels](imagick.importimagepixels) — Imports image pixels * [Imagick::inverseFourierTransformImage](imagick.inversefouriertransformimage) — Description * [Imagick::labelImage](imagick.labelimage) — Adds a label to an image * [Imagick::levelImage](imagick.levelimage) — Adjusts the levels of an image * [Imagick::linearStretchImage](imagick.linearstretchimage) — Stretches with saturation the image intensity * [Imagick::liquidRescaleImage](imagick.liquidrescaleimage) — Animates an image or images * [Imagick::listRegistry](imagick.listregistry) — Description * [Imagick::magnifyImage](imagick.magnifyimage) — Scales an image proportionally 2x * [Imagick::mapImage](imagick.mapimage) — Replaces the colors of an image with the closest color from a reference image * [Imagick::matteFloodfillImage](imagick.mattefloodfillimage) — Changes the transparency value of a color * [Imagick::medianFilterImage](imagick.medianfilterimage) — Applies a digital filter * [Imagick::mergeImageLayers](imagick.mergeimagelayers) — Merges image layers * [Imagick::minifyImage](imagick.minifyimage) — Scales an image proportionally to half its size * [Imagick::modulateImage](imagick.modulateimage) — Control the brightness, saturation, and hue * [Imagick::montageImage](imagick.montageimage) — Creates a composite image * [Imagick::morphImages](imagick.morphimages) — Method morphs a set of images * [Imagick::morphology](imagick.morphology) — Description * [Imagick::mosaicImages](imagick.mosaicimages) — Forms a mosaic from images * [Imagick::motionBlurImage](imagick.motionblurimage) — Simulates motion blur * [Imagick::negateImage](imagick.negateimage) — Negates the colors in the reference image * [Imagick::newImage](imagick.newimage) — Creates a new image * [Imagick::newPseudoImage](imagick.newpseudoimage) — Creates a new image * [Imagick::nextImage](imagick.nextimage) — Moves to the next image * [Imagick::normalizeImage](imagick.normalizeimage) — Enhances the contrast of a color image * [Imagick::oilPaintImage](imagick.oilpaintimage) — Simulates an oil painting * [Imagick::opaquePaintImage](imagick.opaquepaintimage) — Changes the color value of any pixel that matches target * [Imagick::optimizeImageLayers](imagick.optimizeimagelayers) — Removes repeated portions of images to optimize * [Imagick::orderedPosterizeImage](imagick.orderedposterizeimage) — Performs an ordered dither * [Imagick::paintFloodfillImage](imagick.paintfloodfillimage) — Changes the color value of any pixel that matches target * [Imagick::paintOpaqueImage](imagick.paintopaqueimage) — Change any pixel that matches color * [Imagick::paintTransparentImage](imagick.painttransparentimage) — Changes any pixel that matches color with the color defined by fill * [Imagick::pingImage](imagick.pingimage) — Fetch basic attributes about the image * [Imagick::pingImageBlob](imagick.pingimageblob) — Quickly fetch attributes * [Imagick::pingImageFile](imagick.pingimagefile) — Get basic image attributes in a lightweight manner * [Imagick::polaroidImage](imagick.polaroidimage) — Simulates a Polaroid picture * [Imagick::posterizeImage](imagick.posterizeimage) — Reduces the image to a limited number of color level * [Imagick::previewImages](imagick.previewimages) — Quickly pin-point appropriate parameters for image processing * [Imagick::previousImage](imagick.previousimage) — Move to the previous image in the object * [Imagick::profileImage](imagick.profileimage) — Adds or removes a profile from an image * [Imagick::quantizeImage](imagick.quantizeimage) — Analyzes the colors within a reference image * [Imagick::quantizeImages](imagick.quantizeimages) — Analyzes the colors within a sequence of images * [Imagick::queryFontMetrics](imagick.queryfontmetrics) — Returns an array representing the font metrics * [Imagick::queryFonts](imagick.queryfonts) — Returns the configured fonts * [Imagick::queryFormats](imagick.queryformats) — Returns formats supported by Imagick * [Imagick::radialBlurImage](imagick.radialblurimage) — Radial blurs an image * [Imagick::raiseImage](imagick.raiseimage) — Creates a simulated 3d button-like effect * [Imagick::randomThresholdImage](imagick.randomthresholdimage) — Creates a high-contrast, two-color image * [Imagick::readImage](imagick.readimage) — Reads image from filename * [Imagick::readImageBlob](imagick.readimageblob) — Reads image from a binary string * [Imagick::readImageFile](imagick.readimagefile) — Reads image from open filehandle * [Imagick::readimages](imagick.readimages) — Description * [Imagick::recolorImage](imagick.recolorimage) — Recolors image * [Imagick::reduceNoiseImage](imagick.reducenoiseimage) — Smooths the contours of an image * [Imagick::remapImage](imagick.remapimage) — Remaps image colors * [Imagick::removeImage](imagick.removeimage) — Removes an image from the image list * [Imagick::removeImageProfile](imagick.removeimageprofile) — Removes the named image profile and returns it * [Imagick::render](imagick.render) — Renders all preceding drawing commands * [Imagick::resampleImage](imagick.resampleimage) — Resample image to desired resolution * [Imagick::resetImagePage](imagick.resetimagepage) — Reset image page * [Imagick::resizeImage](imagick.resizeimage) — Scales an image * [Imagick::rollImage](imagick.rollimage) — Offsets an image * [Imagick::rotateImage](imagick.rotateimage) — Rotates an image * [Imagick::rotationalBlurImage](imagick.rotationalblurimage) — Description * [Imagick::roundCorners](imagick.roundcorners) — Rounds image corners * [Imagick::sampleImage](imagick.sampleimage) — Scales an image with pixel sampling * [Imagick::scaleImage](imagick.scaleimage) — Scales the size of an image * [Imagick::segmentImage](imagick.segmentimage) — Segments an image * [Imagick::selectiveBlurImage](imagick.selectiveblurimage) — Description * [Imagick::separateImageChannel](imagick.separateimagechannel) — Separates a channel from the image * [Imagick::sepiaToneImage](imagick.sepiatoneimage) — Sepia tones an image * [Imagick::setBackgroundColor](imagick.setbackgroundcolor) — Sets the object's default background color * [Imagick::setColorspace](imagick.setcolorspace) — Set colorspace * [Imagick::setCompression](imagick.setcompression) — Sets the object's default compression type * [Imagick::setCompressionQuality](imagick.setcompressionquality) — Sets the object's default compression quality * [Imagick::setFilename](imagick.setfilename) — Sets the filename before you read or write the image * [Imagick::setFirstIterator](imagick.setfirstiterator) — Sets the Imagick iterator to the first image * [Imagick::setFont](imagick.setfont) — Sets font * [Imagick::setFormat](imagick.setformat) — Sets the format of the Imagick object * [Imagick::setGravity](imagick.setgravity) — Sets the gravity * [Imagick::setImage](imagick.setimage) — Replaces image in the object * [Imagick::setImageAlphaChannel](imagick.setimagealphachannel) — Sets image alpha channel * [Imagick::setImageArtifact](imagick.setimageartifact) — Set image artifact * [Imagick::setImageAttribute](imagick.setimageattribute) — Description * [Imagick::setImageBackgroundColor](imagick.setimagebackgroundcolor) — Sets the image background color * [Imagick::setImageBias](imagick.setimagebias) — Sets the image bias for any method that convolves an image * [Imagick::setImageBiasQuantum](imagick.setimagebiasquantum) — Description * [Imagick::setImageBluePrimary](imagick.setimageblueprimary) — Sets the image chromaticity blue primary point * [Imagick::setImageBorderColor](imagick.setimagebordercolor) — Sets the image border color * [Imagick::setImageChannelDepth](imagick.setimagechanneldepth) — Sets the depth of a particular image channel * [Imagick::setImageClipMask](imagick.setimageclipmask) — Sets image clip mask * [Imagick::setImageColormapColor](imagick.setimagecolormapcolor) — Sets the color of the specified colormap index * [Imagick::setImageColorspace](imagick.setimagecolorspace) — Sets the image colorspace * [Imagick::setImageCompose](imagick.setimagecompose) — Sets the image composite operator * [Imagick::setImageCompression](imagick.setimagecompression) — Sets the image compression * [Imagick::setImageCompressionQuality](imagick.setimagecompressionquality) — Sets the image compression quality * [Imagick::setImageDelay](imagick.setimagedelay) — Sets the image delay * [Imagick::setImageDepth](imagick.setimagedepth) — Sets the image depth * [Imagick::setImageDispose](imagick.setimagedispose) — Sets the image disposal method * [Imagick::setImageExtent](imagick.setimageextent) — Sets the image size * [Imagick::setImageFilename](imagick.setimagefilename) — Sets the filename of a particular image * [Imagick::setImageFormat](imagick.setimageformat) — Sets the format of a particular image * [Imagick::setImageGamma](imagick.setimagegamma) — Sets the image gamma * [Imagick::setImageGravity](imagick.setimagegravity) — Sets the image gravity * [Imagick::setImageGreenPrimary](imagick.setimagegreenprimary) — Sets the image chromaticity green primary point * [Imagick::setImageIndex](imagick.setimageindex) — Set the iterator position * [Imagick::setImageInterlaceScheme](imagick.setimageinterlacescheme) — Sets the image compression * [Imagick::setImageInterpolateMethod](imagick.setimageinterpolatemethod) — Sets the image interpolate pixel method * [Imagick::setImageIterations](imagick.setimageiterations) — Sets the image iterations * [Imagick::setImageMatte](imagick.setimagematte) — Sets the image matte channel * [Imagick::setImageMatteColor](imagick.setimagemattecolor) — Sets the image matte color * [Imagick::setImageOpacity](imagick.setimageopacity) — Sets the image opacity level * [Imagick::setImageOrientation](imagick.setimageorientation) — Sets the image orientation * [Imagick::setImagePage](imagick.setimagepage) — Sets the page geometry of the image * [Imagick::setImageProfile](imagick.setimageprofile) — Adds a named profile to the Imagick object * [Imagick::setImageProperty](imagick.setimageproperty) — Sets an image property * [Imagick::setImageRedPrimary](imagick.setimageredprimary) — Sets the image chromaticity red primary point * [Imagick::setImageRenderingIntent](imagick.setimagerenderingintent) — Sets the image rendering intent * [Imagick::setImageResolution](imagick.setimageresolution) — Sets the image resolution * [Imagick::setImageScene](imagick.setimagescene) — Sets the image scene * [Imagick::setImageTicksPerSecond](imagick.setimagetickspersecond) — Sets the image ticks-per-second * [Imagick::setImageType](imagick.setimagetype) — Sets the image type * [Imagick::setImageUnits](imagick.setimageunits) — Sets the image units of resolution * [Imagick::setImageVirtualPixelMethod](imagick.setimagevirtualpixelmethod) — Sets the image virtual pixel method * [Imagick::setImageWhitePoint](imagick.setimagewhitepoint) — Sets the image chromaticity white point * [Imagick::setInterlaceScheme](imagick.setinterlacescheme) — Sets the image compression * [Imagick::setIteratorIndex](imagick.setiteratorindex) — Set the iterator position * [Imagick::setLastIterator](imagick.setlastiterator) — Sets the Imagick iterator to the last image * [Imagick::setOption](imagick.setoption) — Set an option * [Imagick::setPage](imagick.setpage) — Sets the page geometry of the Imagick object * [Imagick::setPointSize](imagick.setpointsize) — Sets point size * [Imagick::setProgressMonitor](imagick.setprogressmonitor) — Description * [Imagick::setRegistry](imagick.setregistry) — Description * [Imagick::setResolution](imagick.setresolution) — Sets the image resolution * [Imagick::setResourceLimit](imagick.setresourcelimit) — Sets the limit for a particular resource * [Imagick::setSamplingFactors](imagick.setsamplingfactors) — Sets the image sampling factors * [Imagick::setSize](imagick.setsize) — Sets the size of the Imagick object * [Imagick::setSizeOffset](imagick.setsizeoffset) — Sets the size and offset of the Imagick object * [Imagick::setType](imagick.settype) — Sets the image type attribute * [Imagick::shadeImage](imagick.shadeimage) — Creates a 3D effect * [Imagick::shadowImage](imagick.shadowimage) — Simulates an image shadow * [Imagick::sharpenImage](imagick.sharpenimage) — Sharpens an image * [Imagick::shaveImage](imagick.shaveimage) — Shaves pixels from the image edges * [Imagick::shearImage](imagick.shearimage) — Creating a parallelogram * [Imagick::sigmoidalContrastImage](imagick.sigmoidalcontrastimage) — Adjusts the contrast of an image * [Imagick::sketchImage](imagick.sketchimage) — Simulates a pencil sketch * [Imagick::smushImages](imagick.smushimages) — Description * [Imagick::solarizeImage](imagick.solarizeimage) — Applies a solarizing effect to the image * [Imagick::sparseColorImage](imagick.sparsecolorimage) — Interpolates colors * [Imagick::spliceImage](imagick.spliceimage) — Splices a solid color into the image * [Imagick::spreadImage](imagick.spreadimage) — Randomly displaces each pixel in a block * [Imagick::statisticImage](imagick.statisticimage) — Description * [Imagick::steganoImage](imagick.steganoimage) — Hides a digital watermark within the image * [Imagick::stereoImage](imagick.stereoimage) — Composites two images * [Imagick::stripImage](imagick.stripimage) — Strips an image of all profiles and comments * [Imagick::subImageMatch](imagick.subimagematch) — Description * [Imagick::swirlImage](imagick.swirlimage) — Swirls the pixels about the center of the image * [Imagick::textureImage](imagick.textureimage) — Repeatedly tiles the texture image * [Imagick::thresholdImage](imagick.thresholdimage) — Changes the value of individual pixels based on a threshold * [Imagick::thumbnailImage](imagick.thumbnailimage) — Changes the size of an image * [Imagick::tintImage](imagick.tintimage) — Applies a color vector to each pixel in the image * [Imagick::\_\_toString](imagick.tostring) — Returns the image as a string * [Imagick::transformImage](imagick.transformimage) — Convenience method for setting crop size and the image geometry * [Imagick::transformImageColorspace](imagick.transformimagecolorspace) — Transforms an image to a new colorspace * [Imagick::transparentPaintImage](imagick.transparentpaintimage) — Paints pixels transparent * [Imagick::transposeImage](imagick.transposeimage) — Creates a vertical mirror image * [Imagick::transverseImage](imagick.transverseimage) — Creates a horizontal mirror image * [Imagick::trimImage](imagick.trimimage) — Remove edges from the image * [Imagick::uniqueImageColors](imagick.uniqueimagecolors) — Discards all but one of any pixel color * [Imagick::unsharpMaskImage](imagick.unsharpmaskimage) — Sharpens an image * [Imagick::valid](imagick.valid) — Checks if the current item is valid * [Imagick::vignetteImage](imagick.vignetteimage) — Adds vignette filter to the image * [Imagick::waveImage](imagick.waveimage) — Applies wave filter to the image * [Imagick::whiteThresholdImage](imagick.whitethresholdimage) — Force all pixels above the threshold into white * [Imagick::writeImage](imagick.writeimage) — Writes an image to the specified filename * [Imagick::writeImageFile](imagick.writeimagefile) — Writes an image to a filehandle * [Imagick::writeImages](imagick.writeimages) — Writes an image or image sequence * [Imagick::writeImagesFile](imagick.writeimagesfile) — Writes frames to a filehandle
programming_docs
php xml_get_current_line_number xml\_get\_current\_line\_number =============================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_get\_current\_line\_number — Get current line number for an XML parser ### Description ``` xml_get_current_line_number(XMLParser $parser): int ``` Gets the current line number for the given XML parser. ### Parameters `parser` A reference to the XML parser to get line number from. ### Return Values This function returns **`false`** if `parser` does not refer to a valid parser, or else it returns which line the parser is currently at in its data buffer. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | ### See Also * [xml\_get\_current\_column\_number()](function.xml-get-current-column-number) - Get current column number for an XML parser * [xml\_get\_current\_byte\_index()](function.xml-get-current-byte-index) - Get current byte index for an XML parser php shm_detach shm\_detach =========== (PHP 4, PHP 5, PHP 7, PHP 8) shm\_detach — Disconnects from shared memory segment ### Description ``` shm_detach(SysvSharedMemory $shm): bool ``` **shm\_detach()** disconnects from the shared memory given by the `shm` created by [shm\_attach()](function.shm-attach). Remember, that shared memory still exist in the Unix system and the data is still present. ### Parameters `shm` A shared memory segment obtained from [shm\_attach()](function.shm-attach). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `shm` expects a [SysvSharedMemory](class.sysvsharedmemory) instance now; previously, a resource was expected. | ### See Also * [shm\_attach()](function.shm-attach) - Creates or open a shared memory segment * [shm\_remove()](function.shm-remove) - Removes shared memory from Unix systems * [shm\_remove\_var()](function.shm-remove-var) - Removes a variable from shared memory php tempnam tempnam ======= (PHP 4, PHP 5, PHP 7, PHP 8) tempnam — Create file with unique file name ### Description ``` tempnam(string $directory, string $prefix): string|false ``` Creates a file with a unique filename, with access permission set to 0600, in the specified directory. If the directory does not exist or is not writable, **tempnam()** may generate a file in the system's temporary directory, and return the full path to that file, including its name. ### Parameters `directory` The directory where the temporary filename will be created. `prefix` The prefix of the generated temporary filename. > **Note**: Only the first 63 characters of the prefix are used, the rest are ignored. Windows uses only the first three characters of the prefix. > > ### Return Values Returns the new temporary filename (with path), or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | **tempnam()** now emits a notice when falling back to the temp directory of the system. | ### Examples **Example #1 **tempnam()** example** ``` <?php $tmpfname = tempnam("/tmp", "FOO"); $handle = fopen($tmpfname, "w"); fwrite($handle, "writing to tempfile"); fclose($handle); // do something here unlink($tmpfname); ?> ``` ### Notes > **Note**: If PHP cannot create a file in the specified `directory` parameter, it falls back on the system default. On NTFS this also happens if the specified `directory` contains more than 65534 files. > > ### See Also * [tmpfile()](function.tmpfile) - Creates a temporary file * [sys\_get\_temp\_dir()](function.sys-get-temp-dir) - Returns directory path used for temporary files * [unlink()](function.unlink) - Deletes a file php odbc_rollback odbc\_rollback ============== (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_rollback — Rollback a transaction ### Description ``` odbc_rollback(resource $odbc): bool ``` Rolls back all pending statements on the connection. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. ### Return Values Returns **`true`** on success or **`false`** on failure. php mcrypt_module_open mcrypt\_module\_open ==================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_module\_open — Opens the module of the algorithm and the mode to be used **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_module_open( string $algorithm, string $algorithm_directory, string $mode, string $mode_directory ): resource ``` This function opens the module of the algorithm and the mode to be used. The name of the algorithm is specified in algorithm, e.g. `"twofish"` or is one of the **`MCRYPT_ciphername`** constants. The module is closed by calling [mcrypt\_module\_close()](function.mcrypt-module-close). ### Parameters `algorithm` One of the **`MCRYPT_ciphername`** constants, or the name of the algorithm as string. `algorithm_directory` The `algorithm_directory` parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (`""`), the value set by the `mcrypt.algorithms_dir` php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled into libmcrypt (usually /usr/local/lib/libmcrypt). `mode` One of the **`MCRYPT_MODE_modename`** constants, or one of the following strings: "ecb", "cbc", "cfb", "ofb", "nofb" or "stream". `mode_directory` The `mode_directory` parameter is used to locate the encryption module. When you supply a directory name, it is used. When you set it to an empty string (`""`), the value set by the `mcrypt.modes_dir` php.ini directive is used. When it is not set, the default directory that is used is the one that was compiled-in into libmcrypt (usually /usr/local/lib/libmcrypt). ### Return Values Normally it returns an encryption descriptor, or **`false`** on error. ### Examples **Example #1 **mcrypt\_module\_open()** Examples** ``` <?php     $td = mcrypt_module_open(MCRYPT_DES, '',         MCRYPT_MODE_ECB, '/usr/lib/mcrypt-modes');     $td = mcrypt_module_open('rijndael-256', '', 'ofb', ''); ?> ``` The first line in the example above will try to open the `DES` cipher from the default directory and the `ECB` mode from the directory /usr/lib/mcrypt-modes. The second example uses strings as name for the cipher and mode, this only works when the extension is linked against libmcrypt 2.4.x or 2.5.x. **Example #2 Using **mcrypt\_module\_open()** in encryption** ``` <?php     /* Open the cipher */     $td = mcrypt_module_open('rijndael-256', '', 'ofb', '');     /* Create the IV and determine the keysize length, use MCRYPT_RAND      * on Windows instead */     $iv = mcrypt_create_iv(mcrypt_enc_get_iv_size($td), MCRYPT_DEV_RANDOM);     $ks = mcrypt_enc_get_key_size($td);     /* Create key */     $key = substr(md5('very secret key'), 0, $ks);     /* Intialize encryption */     mcrypt_generic_init($td, $key, $iv);     /* Encrypt data */     $encrypted = mcrypt_generic($td, 'This is very important data');     /* Terminate encryption handler */     mcrypt_generic_deinit($td);     /* Initialize encryption module for decryption */     mcrypt_generic_init($td, $key, $iv);     /* Decrypt encrypted string */     $decrypted = mdecrypt_generic($td, $encrypted);     /* Terminate decryption handle and close module */     mcrypt_generic_deinit($td);     mcrypt_module_close($td);     /* Show string */     echo trim($decrypted) . "\n"; ?> ``` ### See Also * [mcrypt\_module\_close()](function.mcrypt-module-close) - Closes the mcrypt module * [mcrypt\_generic()](function.mcrypt-generic) - This function encrypts data * [mdecrypt\_generic()](function.mdecrypt-generic) - Decrypts data * [mcrypt\_generic\_init()](function.mcrypt-generic-init) - This function initializes all buffers needed for encryption * [mcrypt\_generic\_deinit()](function.mcrypt-generic-deinit) - This function deinitializes an encryption module php Stomp::__destruct Stomp::\_\_destruct =================== stomp\_close ============ (PECL stomp >= 0.1.0) Stomp::\_\_destruct -- stomp\_close — Closes stomp connection ### Description Object-oriented style (destructor): public **Stomp::\_\_destruct**() Procedural style: ``` stomp_close(resource $link): bool ``` Closes a previously opened connection. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples See [stomp\_connect()](stomp.construct). php stats_rand_gen_beta stats\_rand\_gen\_beta ====================== (PECL stats >= 1.0.0) stats\_rand\_gen\_beta — Generates a random deviate from the beta distribution ### Description ``` stats_rand_gen_beta(float $a, float $b): float ``` Returns a random deviate from the beta distribution with parameters A and B. The density of the beta is x^(a-1) \* (1-x)^(b-1) / B(a,b) for 0 < x <. Method R. C. H. Cheng. ### Parameters `a` The shape parameter of the beta distribution `b` The shape parameter of the beta distribution ### Return Values A random deviate php Yaf_Request_Http::isXmlHttpRequest Yaf\_Request\_Http::isXmlHttpRequest ==================================== (Yaf >=1.0.0) Yaf\_Request\_Http::isXmlHttpRequest — Determin if request is Ajax Request ### Description ``` public Yaf_Request_Http::isXmlHttpRequest(): bool ``` Check the request whether it is a Ajax Request. > > **Note**: > > > This method depends on the request header: HTTP\_X\_REQUESTED\_WITH, some Javascript library doesn't set this header while doing Ajax request > > ### Parameters This function has no parameters. ### Return Values boolean php ftp_pwd ftp\_pwd ======== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_pwd — Returns the current directory name ### Description ``` ftp_pwd(FTP\Connection $ftp): string|false ``` ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. ### Return Values Returns the current directory name or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_pwd()** example** ``` <?php // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // change directory to public_html ftp_chdir($ftp, 'public_html'); // print current directory echo ftp_pwd($ftp); // /public_html // close the connection ftp_close($ftp); ?> ``` ### See Also * [ftp\_chdir()](function.ftp-chdir) - Changes the current directory on a FTP server * [ftp\_cdup()](function.ftp-cdup) - Changes to the parent directory php Imagick::setRegistry Imagick::setRegistry ==================== (PECL imagick 3 >= 3.3.0) Imagick::setRegistry — Description ### Description ``` public static Imagick::setRegistry(string $key, string $value): bool ``` Sets the ImageMagick registry entry named key to value. This is most useful for setting "temporary-path" which controls where ImageMagick creates temporary images e.g. while processing PDFs. ### Parameters `key` `value` ### Return Values Returns **`true`** on success. php ImagickKernel::scale ImagickKernel::scale ==================== (PECL imagick >= 3.3.0) ImagickKernel::scale — Description ### Description ``` public ImagickKernel::scale(float $scale, int $normalizeFlag = ?): void ``` ScaleKernelInfo() scales the given kernel list by the given amount, with or without normalization of the sum of the kernel values (as per given flags). The exact behaviour of this function depends on the normalization type being used please see http://www.imagemagick.org/api/morphology.php#ScaleKernelInfo for details. Flag should be one of Imagick::NORMALIZE\_KERNEL\_VALUE, Imagick::NORMALIZE\_KERNEL\_CORRELATE, Imagick::NORMALIZE\_KERNEL\_PERCENT or not set. ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **ImagickKernel::scale()**** ``` <?php     function renderKernelTable($matrix) {         $output = "<table class='infoTable'>";              foreach ($matrix as $row) {             $output .= "<tr>";             foreach ($row as $cell) {                 $output .= "<td style='text-align:left'>";                 if ($cell === false) {                     $output .= "false";                 }                 else {                     $output .= round($cell, 3);                 }                 $output .= "</td>";             }             $output .= "</tr>";         }              $output .= "</table>";              return $output;     }     $output = "";          $matrix = [         [-1, 0, -1],         [ 0, 4,  0],         [-1, 0, -1],     ];     $kernel = \ImagickKernel::fromMatrix($matrix);     $kernelClone = clone $kernel;     $output .= "Start kernel<br/>";     $output .= renderKernelTable($kernel->getMatrix());               $output .= "Scaling with NORMALIZE_KERNEL_VALUE. The  <br/>";     $kernel->scale(2, \Imagick::NORMALIZE_KERNEL_VALUE);     $output .= renderKernelTable($kernel->getMatrix());     $kernel = clone $kernelClone;     $output .= "Scaling by percent<br/>";     $kernel->scale(2, \Imagick::NORMALIZE_KERNEL_PERCENT);     $output .= renderKernelTable($kernel->getMatrix());          $matrix2 = [         [-1, -1, 1],         [ -1, false,  1],         [1, 1, 1],     ];          $kernel = \ImagickKernel::fromMatrix($matrix2);     $output .= "Scaling by correlate<br/>";     $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_CORRELATE);     $output .= renderKernelTable($kernel->getMatrix());     return $output;  ?> ``` php fdf_get_attachment fdf\_get\_attachment ==================== (PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_get\_attachment — Extracts uploaded file embedded in the FDF ### Description ``` fdf_get_attachment(resource $fdf_document, string $fieldname, string $savepath): array ``` Extracts a file uploaded by means of the "file selection" field `fieldname` and stores it under `savepath`. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `fieldname` `savepath` May be the name of a plain file or an existing directory in which the file is to be created under its original name. Any existing file under the same name will be overwritten. > > **Note**: > > > There seems to be no other way to find out the original filename but to store the file using a directory as `savepath` and check for the basename it was stored under. > > ### Return Values The returned array contains the following fields: * `path` - path were the file got stored * `size` - size of the stored file in bytes * `type` - mimetype if given in the FDF ### Examples **Example #1 Storing an uploaded file** ``` <?php   $fdf = fdf_open_string($HTTP_FDF_DATA);   $data = fdf_get_attachment($fdf, "filename", "/tmpdir");   echo "The uploaded file is stored in $data[path]"; ?> ``` php SolrQuery::removeFacetDateField SolrQuery::removeFacetDateField =============================== (PECL solr >= 0.9.2) SolrQuery::removeFacetDateField — Removes one of the facet date fields ### Description ``` public SolrQuery::removeFacetDateField(string $field): SolrQuery ``` The name of the field ### Parameters `field` The name of the date field to remove ### Return Values Returns the current SolrQuery object, if the return value is used. php Gmagick::getpackagename Gmagick::getpackagename ======================= (PECL gmagick >= Unknown) Gmagick::getpackagename — Returns the GraphicsMagick package name ### Description ``` public Gmagick::getpackagename(): string ``` Returns the GraphicsMagick package name. ### Parameters This function has no parameters. ### Return Values Returns the GraphicsMagick package name as a string. ### Errors/Exceptions Throws an **GmagickException** on error. php runkit7_function_redefine runkit7\_function\_redefine =========================== (PECL runkit7 >= Unknown) runkit7\_function\_redefine — Replace a function definition with a new implementation ### Description ``` runkit7_function_redefine( string $function_name, string $argument_list, string $code, bool $return_by_reference = null, string $doc_comment = null, string $return_type = ?, bool $is_strict = ? ): bool ``` ``` runkit7_function_redefine( string $function_name, Closure $closure, string $doc_comment = null, string $return_type = ?, bool $is_strict = ? ): bool ``` > **Note**: By default, only userspace functions may be removed, renamed, or modified. In order to override internal functions, you must enable the `runkit.internal_override` setting in php.ini. > > ### Parameters `function_name` Name of function to redefine `argument_list` New list of arguments to be accepted by function `code` New code implementation `closure` A [closure](class.closure) that defines the function. `return_by_reference` Whether the function should return by reference. `doc_comment` The doc comment of the function. `return_type` The return type of the function. `is_strict` Whether the function behaves as if it was declared in a file with `strict_types=1` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 A **runkit7\_function\_redefine()** example** ``` <?php function testme() {   echo "Original Testme Implementation\n"; } testme(); runkit7_function_redefine('testme','','echo "New Testme Implementation\n";'); testme(); ?> ``` The above example will output: ``` Original Testme Implementation New Testme Implementation ``` ### See Also * [runkit7\_function\_add()](function.runkit7-function-add) - Add a new function, similar to create\_function * [runkit7\_function\_copy()](function.runkit7-function-copy) - Copy a function to a new function name * [runkit7\_function\_rename()](function.runkit7-function-rename) - Change a function's name * [runkit7\_function\_remove()](function.runkit7-function-remove) - Remove a function definition * [runkit7\_method\_redefine()](function.runkit7-method-redefine) - Dynamically changes the code of the given method php EventBuffer::expand EventBuffer::expand =================== (PECL event >= 1.2.6-beta) EventBuffer::expand — Reserves space in buffer ### Description ``` public EventBuffer::expand( int $len ): bool ``` Alters the last chunk of memory in the buffer, or adds a new chunk, such that the buffer is now large enough to contain `len` bytes without any further allocations. ### Parameters `len` The number of bytes to reserve for the buffer ### Return Values Returns **`true`** on success or **`false`** on failure. php EventBuffer::copyout EventBuffer::copyout ==================== (PECL event >= 1.2.6-beta) EventBuffer::copyout — Copies out specified number of bytes from the front of the buffer ### Description ``` public EventBuffer::copyout( string &$data , int $max_bytes ): int ``` Behaves just like [EventBuffer::read()](eventbuffer.read) , but does not drain any data from the buffer. I.e. it copies the first `max_bytes` bytes from the front of the buffer into `data` . If there are fewer than `max_bytes` bytes available, the function copies all the bytes there are. ### Parameters `data` Output string. `max_bytes` The number of bytes to copy. ### Return Values Returns the number of bytes copied, or **`-1`** on failure. ### See Also * [EventBuffer::read()](eventbuffer.read) - Read data from an evbuffer and drain the bytes read * [EventBuffer::appendFrom()](eventbuffer.appendfrom) - Moves the specified number of bytes from a source buffer to the end of the current buffer
programming_docs
php imap_msgno imap\_msgno =========== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_msgno — Gets the message sequence number for the given UID ### Description ``` imap_msgno(IMAP\Connection $imap, int $message_uid): int ``` Returns the message sequence number for the given `message_uid`. This function is the inverse of [imap\_uid()](function.imap-uid). ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_uid` The message UID ### Return Values Returns the message sequence number for the given `message_uid`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_uid()](function.imap-uid) - This function returns the UID for the given message sequence number php SplPriorityQueue::getExtractFlags SplPriorityQueue::getExtractFlags ================================= (PHP 7, PHP 8) SplPriorityQueue::getExtractFlags — Get the flags of extraction ### Description ``` public SplPriorityQueue::getExtractFlags(): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns the flags of extraction. php Gmagick::setimageblueprimary Gmagick::setimageblueprimary ============================ (PECL gmagick >= Unknown) Gmagick::setimageblueprimary — Sets the image chromaticity blue primary point ### Description ``` public Gmagick::setimageblueprimary(float $x, float $y): Gmagick ``` Sets the image chromaticity blue primary point. ### Parameters `x` The blue primary x-point. `y` The blue primary y-point. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php SplPriorityQueue::count SplPriorityQueue::count ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::count — Counts the number of elements in the queue ### Description ``` public SplPriorityQueue::count(): int ``` ### Parameters This function has no parameters. ### Return Values Returns the number of elements in the queue. php Gmagick::frameimage Gmagick::frameimage =================== (PECL gmagick >= Unknown) Gmagick::frameimage — Adds a simulated three-dimensional border ### Description ``` public Gmagick::frameimage( GmagickPixel $color, int $width, int $height, int $inner_bevel, int $outer_bevel ): Gmagick ``` Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame. ### Parameters `color` [GmagickPixel](class.gmagickpixel) object or a float representing the matte color. `width` The width of the border. `height` The height of the border. `inner_bevel` The inner bevel width. `outer_bevel` The outer bevel width. ### Return Values The framed [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php libxml_clear_errors libxml\_clear\_errors ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) libxml\_clear\_errors — Clear libxml error buffer ### Description ``` libxml_clear_errors(): void ``` **libxml\_clear\_errors()** clears the libxml error buffer. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [libxml\_get\_errors()](function.libxml-get-errors) - Retrieve array of errors * [libxml\_get\_last\_error()](function.libxml-get-last-error) - Retrieve last error from libxml php Stomp::__construct Stomp::\_\_construct ==================== stomp\_connect ============== (PECL stomp >= 0.1.0) Stomp::\_\_construct -- stomp\_connect — Opens a connection ### Description Object-oriented style (constructor): public **Stomp::\_\_construct**( string `$broker` = ini\_get("stomp.default\_broker\_uri"), string `$username` = ?, string `$password` = ?, array `$headers` = ? ) Procedural style: ``` stomp_connect( string $broker = ini_get("stomp.default_broker_uri"), string $username = ?, string $password = ?, array $headers = ? ): resource ``` Opens a connection to a stomp compliant Message Broker. ### Parameters `broker` The broker URI `username` The username. `password` The password. `headers` Associative array containing the additional headers (example: receipt). ### Return Values > > **Note**: > > > A transaction header may be specified, indicating that the message acknowledgment should be part of the named transaction. > > > ### Changelog | Version | Description | | --- | --- | | PECL stomp 1.0.1 | The `headers` parameter was added | ### Examples **Example #1 Object-oriented style** ``` <?php /* connection */ try {     $stomp = new Stomp('tcp://localhost:61613'); } catch(StompException $e) {     die('Connection failed: ' . $e->getMessage()); } /* close connection */ unset($stomp); ?> ``` **Example #2 Procedural style** ``` <?php /* connection */ $link = stomp_connect('ssl://localhost:61612'); /* check connection */ if (!$link) {     die('Connection failed: ' . stomp_connect_error()); } /* close connection */ stomp_close($link); ?> ``` php RarEntry::isEncrypted RarEntry::isEncrypted ===================== (PECL rar >= 2.0.0) RarEntry::isEncrypted — Test whether an entry is encrypted ### Description ``` public RarEntry::isEncrypted(): bool ``` Tests whether the current entry contents are encrypted. > > **Note**: > > > The password used may differ between files inside the same RAR archive. > > ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the current entry is encrypted and **`false`** otherwise. php fbird_affected_rows fbird\_affected\_rows ===================== (PHP 5, PHP 7 < 7.4.0) fbird\_affected\_rows — Alias of [ibase\_affected\_rows()](function.ibase-affected-rows) ### Description This function is an alias of: [ibase\_affected\_rows()](function.ibase-affected-rows). ### See Also * [fbird\_query()](function.fbird-query) - Alias of ibase\_query * [fbird\_execute()](function.fbird-execute) - Alias of ibase\_execute php The DOMComment class The DOMComment class ==================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents comment nodes, characters delimited by `<!--` and `-->`. Class synopsis -------------- class **DOMComment** extends [DOMCharacterData](class.domcharacterdata) { /\* Inherited properties \*/ public string [$data](class.domcharacterdata#domcharacterdata.props.data); public readonly int [$length](class.domcharacterdata#domcharacterdata.props.length); public readonly ?[DOMElement](class.domelement) [$previousElementSibling](class.domcharacterdata#domcharacterdata.props.previouselementsibling); public readonly ?[DOMElement](class.domelement) [$nextElementSibling](class.domcharacterdata#domcharacterdata.props.nextelementsibling); public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domcomment.construct)(string `$data` = "") /\* Inherited methods \*/ ``` public DOMCharacterData::appendData(string $data): bool ``` ``` public DOMCharacterData::deleteData(int $offset, int $count): bool ``` ``` public DOMCharacterData::insertData(int $offset, string $data): bool ``` ``` public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool ``` ``` public DOMCharacterData::substringData(int $offset, int $count): string|false ``` ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } See Also -------- * [» W3C specification of Comment](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1728279322) Table of Contents ----------------- * [DOMComment::\_\_construct](domcomment.construct) — Creates a new DOMComment object php Ds\Deque::set Ds\Deque::set ============= (PECL ds >= 1.0.0) Ds\Deque::set — Updates a value at a given index ### Description ``` public Ds\Deque::set(int $index, mixed $value): void ``` Updates a value at a given index. ### Parameters `index` The index of the value to update. `value` The new value. ### Return Values No value is returned. ### Errors/Exceptions [OutOfRangeException](class.outofrangeexception) if the index is not valid. ### Examples **Example #1 **Ds\Deque::set()** example** ``` <?php $deque = new \Ds\Deque(["a", "b", "c"]); $deque->set(1, "_"); print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => a [1] => _ [2] => c ) ``` **Example #2 **Ds\Deque::set()** example using array syntax** ``` <?php $deque = new \Ds\Deque(["a", "b", "c"]); $deque[1] = "_"; print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => a [1] => _ [2] => c ) ``` php IntlTimeZone::countEquivalentIDs IntlTimeZone::countEquivalentIDs ================================ intltz\_count\_equivalent\_ids ============================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::countEquivalentIDs -- intltz\_count\_equivalent\_ids — Get the number of IDs in the equivalency group that includes the given ID ### Description Object-oriented style (method): ``` public static IntlTimeZone::countEquivalentIDs(string $timezoneId): int|false ``` Procedural style: ``` intltz_count_equivalent_ids(string $timezoneId): int|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `timezoneId` ### Return Values php SolrQuery::getHighlightFormatter SolrQuery::getHighlightFormatter ================================ (PECL solr >= 0.9.2) SolrQuery::getHighlightFormatter — Returns the formatter for the highlighted output ### Description ``` public SolrQuery::getHighlightFormatter(string $field_override = ?): string ``` Returns the formatter for the highlighted output ### Parameters `field_override` The name of the field ### Return Values Returns a string on success and **`null`** if not set. php IntlIterator::rewind IntlIterator::rewind ==================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlIterator::rewind — Rewind the iterator to the first element ### Description ``` public IntlIterator::rewind(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php vprintf vprintf ======= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) vprintf — Output a formatted string ### Description ``` vprintf(string $format, array $values): int ``` Display array values as a formatted string according to `format` (which is described in the documentation for [sprintf()](function.sprintf)). Operates as [printf()](function.printf) but accepts an array of arguments, rather than a variable number of arguments. ### Parameters `format` The format string is composed of zero or more directives: ordinary characters (excluding `%`) that are copied directly to the result and *conversion specifications*, each of which results in fetching its own parameter. A conversion specification follows this prototype: `%[argnum$][flags][width][.precision]specifier`. ##### Argnum An integer followed by a dollar sign `$`, to specify which number argument to treat in the conversion. **Flags**| Flag | Description | | --- | --- | | `-` | Left-justify within the given field width; Right justification is the default | | `+` | Prefix positive numbers with a plus sign `+`; Default only negative are prefixed with a negative sign. | | (space) | Pads the result with spaces. This is the default. | | `0` | Only left-pads numbers with zeros. With `s` specifiers this can also right-pad with zeros. | | `'`(char) | Pads the result with the character (char). | ##### Width An integer that says how many characters (minimum) this conversion should result in. ##### Precision A period `.` followed by an integer who's meaning depends on the specifier: * For `e`, `E`, `f` and `F` specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). * For `g`, `G`, `h` and `H` specifiers: this is the maximum number of significant digits to be printed. * For `s` specifier: it acts as a cutoff point, setting a maximum character limit to the string. > **Note**: If the period is specified without an explicit value for precision, 0 is assumed. > > > **Note**: Attempting to use a position specifier greater than **`PHP_INT_MAX`** will generate warnings. > > **Specifiers**| Specifier | Description | | --- | --- | | `%` | A literal percent character. No argument is required. | | `b` | The argument is treated as an integer and presented as a binary number. | | `c` | The argument is treated as an integer and presented as the character with that ASCII. | | `d` | The argument is treated as an integer and presented as a (signed) decimal number. | | `e` | The argument is treated as scientific notation (e.g. 1.2e+2). | | `E` | Like the `e` specifier but uses uppercase letter (e.g. 1.2E+2). | | `f` | The argument is treated as a float and presented as a floating-point number (locale aware). | | `F` | The argument is treated as a float and presented as a floating-point number (non-locale aware). | | `g` | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. | | `G` | Like the `g` specifier but uses `E` and `f`. | | `h` | Like the `g` specifier but uses `F`. Available as of PHP 8.0.0. | | `H` | Like the `g` specifier but uses `E` and `F`. Available as of PHP 8.0.0. | | `o` | The argument is treated as an integer and presented as an octal number. | | `s` | The argument is treated and presented as a string. | | `u` | The argument is treated as an integer and presented as an unsigned decimal number. | | `x` | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). | | `X` | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). | **Warning** The `c` type specifier ignores padding and width **Warning** Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results Variables will be co-erced to a suitable type for the specifier: **Type Handling**| Type | Specifiers | | --- | --- | | string | `s` | | int | `d`, `u`, `c`, `o`, `x`, `X`, `b` | | float | `e`, `E`, `f`, `F`, `g`, `G`, `h`, `H` | `values` ### Return Values Returns the length of the outputted string. ### Examples **Example #1 **vprintf()**: zero-padded integers** ``` <?php vprintf("%04d-%02d-%02d", explode('-', '1988-8-1')); ?> ``` The above example will output: ``` 1988-08-01 ``` ### See Also * [printf()](function.printf) - Output a formatted string * [sprintf()](function.sprintf) - Return a formatted string * [fprintf()](function.fprintf) - Write a formatted string to a stream * [vsprintf()](function.vsprintf) - Return a formatted string * [vfprintf()](function.vfprintf) - Write a formatted string to a stream * [sscanf()](function.sscanf) - Parses input from a string according to a format * [fscanf()](function.fscanf) - Parses input from a file according to a format * [number\_format()](function.number-format) - Format a number with grouped thousands * [date()](function.date) - Format a Unix timestamp php openssl_open openssl\_open ============= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) openssl\_open — Open sealed data ### Description ``` openssl_open( string $data, string &$output, string $encrypted_key, OpenSSLAsymmetricKey|OpenSSLCertificate|array|string $private_key, string $cipher_algo, ?string $iv = null ): bool ``` **openssl\_open()** opens (decrypts) `data` using the private key associated with the key identifier `private_key` and the envelope key `encrypted_key`, and fills `output` with the decrypted data. The envelope key is generated when the data are sealed and can only be used by one specific private key. See [openssl\_seal()](function.openssl-seal) for more information. ### Parameters `data` `output` If the call is successful the opened data is returned in this parameter. `encrypted_key` `private_key` `cipher_algo` The cipher method. **Caution** The default value (`'RC4'`) is considered insecure. It is strongly recommended to explicitly specify a secure cipher method. `iv` The initialization vector. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `private_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) or [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` or `OpenSSL X.509 CSR` was accepted. | | 8.0.0 | `cipher_algo` is no longer an optional parameter. | ### Examples **Example #1 **openssl\_open()** example** ``` <?php // $sealed and $env_key are assumed to contain the sealed data // and our envelope key, both given to us by the sealer. // fetch private key from file and ready it $fp = fopen("/src/openssl-0.9.6/demos/sign/key.pem", "r"); $priv_key = fread($fp, 8192); fclose($fp); $pkeyid = openssl_get_privatekey($priv_key); // decrypt the data and store it in $open if (openssl_open($sealed, $open, $env_key, $pkeyid)) {     echo "here is the opened data: ", $open; } else {     echo "failed to open data"; } // free the private key from memory openssl_free_key($pkeyid); ?> ``` ### See Also * [openssl\_seal()](function.openssl-seal) - Seal (encrypt) data
programming_docs
php SNMP::getError SNMP::getError ============== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SNMP::getError — Get last error message ### Description ``` public SNMP::getError(): string ``` Returns string with error from last SNMP request. ### Parameters This function has no parameters. ### Return Values String describing error from last SNMP request. ### Examples **Example #1 **SNMP::getError()** example** ``` <?php $session = new SNMP(SNMP::VERSION_2c, '127.0.0.1', 'boguscommunity'); var_dump(@$session->get('.1.3.6.1.2.1.1.1.0')); var_dump($session->getError()); ?> ``` The above example will output: ``` bool(false) string(26) "No response from 127.0.0.1" ``` ### See Also * [SNMP::getErrno()](snmp.geterrno) - Get last error code php ini_get ini\_get ======== (PHP 4, PHP 5, PHP 7, PHP 8) ini\_get — Gets the value of a configuration option ### Description ``` ini_get(string $option): string|false ``` Returns the value of the configuration option on success. ### Parameters `option` The configuration option name. ### Return Values Returns the value of the configuration option as a string on success, or an empty string for `null` values. Returns **`false`** if the configuration option doesn't exist. ### Examples **Example #1 A few **ini\_get()** examples** ``` <?php /* Our php.ini contains the following settings: display_errors = On register_globals = Off post_max_size = 8M */ echo 'display_errors = ' . ini_get('display_errors') . "\n"; echo 'register_globals = ' . ini_get('register_globals') . "\n"; echo 'post_max_size = ' . ini_get('post_max_size') . "\n"; echo 'post_max_size+1 = ' . (ini_get('post_max_size')+1) . "\n"; echo 'post_max_size in bytes = ' . return_bytes(ini_get('post_max_size')); function return_bytes($val) {     $val = trim($val);     $last = strtolower($val[strlen($val)-1]);     switch($last) {         // The 'G' modifier is available         case 'g':             $val *= 1024;         case 'm':             $val *= 1024;         case 'k':             $val *= 1024;     }     return $val; } ?> ``` The above example will output something similar to: ``` display_errors = 1 register_globals = 0 post_max_size = 8M post_max_size+1 = 9 post_max_size in bytes = 8388608 ``` ### Notes > > **Note**: **When querying boolean values** > > > > A boolean ini value of `off` will be returned as an empty string or "0" while a boolean ini value of `on` will be returned as "1". The function can also return the literal string of INI value. > > > > **Note**: **When querying memory size values** > > > > Many ini memory size values, such as [upload\_max\_filesize](https://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize), are stored in the php.ini file in shorthand notation. **ini\_get()** will return the exact string stored in the php.ini file and *NOT* its int equivalent. Attempting normal arithmetic functions on these values will not have otherwise expected results. The example above shows one way to convert shorthand notation into bytes, much like how the PHP source does it. > > > > **Note**: > > > **ini\_get()** can't read "array" ini options such as pdo.dsn.\*, and returns **`false`** in this case. > > ### See Also * [get\_cfg\_var()](function.get-cfg-var) - Gets the value of a PHP configuration option * [ini\_get\_all()](function.ini-get-all) - Gets all configuration options * [ini\_restore()](function.ini-restore) - Restores the value of a configuration option * [ini\_set()](function.ini-set) - Sets the value of a configuration option php ldap_parse_result ldap\_parse\_result =================== (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) ldap\_parse\_result — Extract information from result ### Description ``` ldap_parse_result( LDAP\Connection $ldap, LDAP\Result $result, int &$error_code, string &$matched_dn = null, string &$error_message = null, array &$referrals = null, array &$controls = null ): bool ``` Parses an LDAP search result. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `result` An [LDAP\Result](class.ldap-result) instance, returned by [ldap\_list()](function.ldap-list) or [ldap\_search()](function.ldap-search). `error_code` A reference to a variable that will be set to the LDAP error code in the result, or `0` if no error occurred. `matched_dn` A reference to a variable that will be set to a matched DN if one was recognised within the request, otherwise it will be set to **`null`**. `error_message` A reference to a variable that will be set to the LDAP error message in the result, or an empty string if no error occurred. `referrals` A reference to a variable that will be set to an array set to all of the referral strings in the result, or an empty array if no referrals were returned. `controls` An array of LDAP Controls which have been sent with the response. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `result` parameter expects an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was expected. | | 7.3.0 | Support for `controls` added | ### Examples **Example #1 **ldap\_parse\_result()** example** ``` <?php $result = ldap_search($ldap, "cn=userref,dc=my-domain,dc=com", "(cn=user*)"); $errcode = $dn = $errmsg = $refs =  null; if (ldap_parse_result($ldap, $result, $errcode, $dn, $errmsg, $refs)) {     // do something with $errcode, $dn, $errmsg and $refs } ?> ``` php pg_lo_tell pg\_lo\_tell ============ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_tell — Returns current seek position a of large object ### Description ``` pg_lo_tell(PgSql\Lob $lob): int ``` **pg\_lo\_tell()** returns the current position (offset from the beginning) of a large object. To use the large object interface, it is necessary to enclose it within a transaction block. ### Parameters `lob` An [PgSql\Lob](class.pgsql-lob) instance, returned by [pg\_lo\_open()](function.pg-lo-open). ### Return Values The current seek offset (in number of bytes) from the beginning of the large object. If there is an error, the return value is negative. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `lob` parameter expects an [PgSql\Lob](class.pgsql-lob) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_tell()** example** ``` <?php    $doc_oid = 189762345;    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $handle = pg_lo_open($database, $doc_oid, "r");    // Skip first 50000 bytes    pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);    // See how far we've skipped    $offset = pg_lo_tell($handle);    echo "Seek position is: $offset";    pg_query($database, "commit"); ?> ``` The above example will output: ``` Seek position is: 50000 ``` ### See Also * [pg\_lo\_seek()](function.pg-lo-seek) - Seeks position within a large object php sodium_crypto_aead_chacha20poly1305_decrypt sodium\_crypto\_aead\_chacha20poly1305\_decrypt =============================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_aead\_chacha20poly1305\_decrypt — Verify then decrypt with ChaCha20-Poly1305 ### Description ``` sodium_crypto_aead_chacha20poly1305_decrypt( string $ciphertext, string $additional_data, string $nonce, string $key ): string|false ``` Verify then decrypt with ChaCha20-Poly1305. ### Parameters `ciphertext` Must be in the format provided by [sodium\_crypto\_aead\_chacha20poly1305\_encrypt()](function.sodium-crypto-aead-chacha20poly1305-encrypt) (ciphertext and tag, concatenated). `additional_data` Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext. `nonce` A number that must be only used once, per message. 8 bytes long. `key` Encryption key (256-bit). ### Return Values Returns the plaintext on success, or **`false`** on failure. php Imagick::setImageIterations Imagick::setImageIterations =========================== (PECL imagick 2, PECL imagick 3) Imagick::setImageIterations — Sets the image iterations ### Description ``` public Imagick::setImageIterations(int $iterations): bool ``` Sets the number of iterations an animated image is repeated. ### Parameters `iterations` The number of iterations the image should loop over. Set to '0' to loop continuously. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Basic **Imagick::setImageIterations()** usage** ``` <?php $imagick = new Imagick(realpath("Test.gif")); $imagick = $imagick->coalesceImages(); $imagick->setImageIterations(1); $imagick = $imagick->deconstructImages(); $imagick->writeImages('/path/to/save/OnceOnly.gif', true); ?> ``` php uopz_rename uopz\_rename ============ (PECL uopz 1, PECL uopz 2) uopz\_rename — Rename a function at runtime **Warning**This function has been *REMOVED* in PECL uopz 5.0.0. ### Description ``` uopz_rename(string $function, string $rename): void ``` ``` uopz_rename(string $class, string $function, string $rename): void ``` Renames `function` to `rename` > > **Note**: > > > If both functions exist, this effectively swaps their names > > ### Parameters `class` The name of the class containing the function `function` The name of an existing function `rename` The new name for the function ### Return Values ### Examples **Example #1 **uopz\_rename()** example** ``` <?php uopz_rename("strlen", "original_strlen"); echo original_strlen("Hello World"); ?> ``` The above example will output: ``` 11 ``` **Example #2 **uopz\_rename()** class example** ``` <?php class My {     public function strlen($arg) {         return strlen($arg);     } } uopz_rename(My::class, "strlen", "original_strlen"); echo My::original_strlen("Hello World"); ?> ``` The above example will output: ``` 11 ``` php fileperms fileperms ========= (PHP 4, PHP 5, PHP 7, PHP 8) fileperms — Gets file permissions ### Description ``` fileperms(string $filename): int|false ``` Gets permissions for the given file. ### Parameters `filename` Path to the file. ### Return Values Returns the file's permissions as a numeric mode. Lower bits of this mode are the same as the permissions expected by [chmod()](function.chmod), however on most platforms the return value will also include information on the type of file given as `filename`. The examples below demonstrate how to test the return value for specific permissions and file types on POSIX systems, including Linux and macOS. For local files, the specific return value is that of the `st_mode` member of the structure returned by the C library's [stat()](function.stat) function. Exactly which bits are set can vary from platform to platform, and looking up your specific platform's documentation is recommended if parsing the non-permission bits of the return value is required. Returns **`false`** on failure. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 Display permissions as an octal value** ``` <?php echo substr(sprintf('%o', fileperms('/tmp')), -4); echo substr(sprintf('%o', fileperms('/etc/passwd')), -4); ?> ``` The above example will output: ``` 1777 0644 ``` **Example #2 Display full permissions** ``` <?php $perms = fileperms('/etc/passwd'); switch ($perms & 0xF000) {     case 0xC000: // socket         $info = 's';         break;     case 0xA000: // symbolic link         $info = 'l';         break;     case 0x8000: // regular         $info = 'r';         break;     case 0x6000: // block special         $info = 'b';         break;     case 0x4000: // directory         $info = 'd';         break;     case 0x2000: // character special         $info = 'c';         break;     case 0x1000: // FIFO pipe         $info = 'p';         break;     default: // unknown         $info = 'u'; } // Owner $info .= (($perms & 0x0100) ? 'r' : '-'); $info .= (($perms & 0x0080) ? 'w' : '-'); $info .= (($perms & 0x0040) ?             (($perms & 0x0800) ? 's' : 'x' ) :             (($perms & 0x0800) ? 'S' : '-')); // Group $info .= (($perms & 0x0020) ? 'r' : '-'); $info .= (($perms & 0x0010) ? 'w' : '-'); $info .= (($perms & 0x0008) ?             (($perms & 0x0400) ? 's' : 'x' ) :             (($perms & 0x0400) ? 'S' : '-')); // World $info .= (($perms & 0x0004) ? 'r' : '-'); $info .= (($perms & 0x0002) ? 'w' : '-'); $info .= (($perms & 0x0001) ?             (($perms & 0x0200) ? 't' : 'x' ) :             (($perms & 0x0200) ? 'T' : '-')); echo $info; ?> ``` The above example will output: ``` -rw-r--r-- ``` ### Notes > **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details. > > **Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [chmod()](function.chmod) - Changes file mode * [is\_readable()](function.is-readable) - Tells whether a file exists and is readable * [stat()](function.stat) - Gives information about a file php Gmagick::chopimage Gmagick::chopimage ================== (PECL gmagick >= Unknown) Gmagick::chopimage — Removes a region of an image and trims ### Description ``` public Gmagick::chopimage( int $width, int $height, int $x, int $y ): Gmagick ``` Removes a region of an image and collapses the image to occupy the removed portion. ### Parameters `width` Width of the chopped area. `height` Height of the chopped area. `x` X origo of the chopped area. `y` Y origo of the chopped area. ### Return Values The chopped [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Yaf_Controller_Abstract::init Yaf\_Controller\_Abstract::init =============================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::init — Controller initializer ### Description ``` public Yaf_Controller_Abstract::init(): void ``` [Yaf\_Controller\_Abstract::\_\_construct()](yaf-controller-abstract.construct) is final, which means users can not override it. but users can define **Yaf\_Controller\_Abstract::init()**, which will be called after controller object is instantiated. ### Parameters This function has no parameters. ### Return Values ### See Also * [Yaf\_Controller\_Abstract::\_\_construct()](yaf-controller-abstract.construct) - Yaf\_Controller\_Abstract constructor php EvStat::__construct EvStat::\_\_construct ===================== (PECL ev >= 0.2.0) EvStat::\_\_construct — Constructs EvStat watcher object ### Description public **EvStat::\_\_construct**( string `$path` , float `$interval` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** , int `$priority` = 0 ) Constructs EvStat watcher object and starts the watcher automatically. ### Parameters `path` The path to wait for status changes on. `interval` Hint on how quickly a change is expected to be detected and should normally be specified as **`0.0`** to let *libev* choose a suitable value. `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Examples **Example #1 Monitor changes of /var/log/messages** ``` <?php // Use 10 second update interval. $w = new EvStat("/var/log/messages", 8, function ($w) {  echo "/var/log/messages changed\n";  $attr = $w->attr();  if ($attr['nlink']) {   printf("Current size: %ld\n", $attr['size']);   printf("Current atime: %ld\n", $attr['atime']);   printf("Current mtime: %ld\n", $attr['mtime']);  } else {   fprintf(STDERR, "`messages` file is not there!");   $w->stop();  } }); Ev::run(); ?> ``` php Imagick::shadeImage Imagick::shadeImage =================== (PECL imagick 2, PECL imagick 3) Imagick::shadeImage — Creates a 3D effect ### Description ``` public Imagick::shadeImage(bool $gray, float $azimuth, float $elevation): bool ``` Shines a distant light on an image to create a three-dimensional effect. You control the positioning of the light with azimuth and elevation; azimuth is measured in degrees off the x axis and elevation is measured in pixels above the Z axis. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `gray` A value other than zero shades the intensity of each pixel. `azimuth` Defines the light source direction. `elevation` Defines the light source direction. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on failure. ### Examples **Example #1 **Imagick::shadeImage()**** ``` <?php function shadeImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->shadeImage(true, 45, 20);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php NumberFormatter::parseCurrency NumberFormatter::parseCurrency ============================== numfmt\_parse\_currency ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::parseCurrency -- numfmt\_parse\_currency — Parse a currency number ### Description Object-oriented style ``` public NumberFormatter::parseCurrency(string $string, string &$currency, int &$offset = null): float|false ``` Procedural style ``` numfmt_parse_currency( NumberFormatter $formatter, string $string, string &$currency, int &$offset = null ): float|false ``` Parse a string into a float and a currency using the current formatter. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. `currency` Parameter to receive the currency name (3-letter ISO 4217 currency code). `offset` Offset in the string at which to begin parsing. On return, this value will hold the offset at which parsing ended. ### Return Values The parsed numeric value or **`false`** on error. ### Examples **Example #1 **numfmt\_parse\_currency()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::CURRENCY ); $num = "1.234.567,89\xc2\xa0$"; echo "We have ".numfmt_parse_currency($fmt, $num, $curr)." in $curr\n"; ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::CURRENCY ); $num = "1.234.567,89\xc2\xa0$"; echo "We have ".$fmt->parseCurrency($num, $curr)." in $curr\n"; ?> ``` The above example will output: ``` We have 1234567.89 in USD ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [numfmt\_parse()](numberformatter.parse) - Parse a number * [numfmt\_format\_currency()](numberformatter.formatcurrency) - Format a currency value
programming_docs
php SolrUpdateResponse::__construct SolrUpdateResponse::\_\_construct ================================= (PECL solr >= 0.9.2) SolrUpdateResponse::\_\_construct — Constructor ### Description public **SolrUpdateResponse::\_\_construct**() Constructor ### Parameters This function has no parameters. ### Return Values None php Phar::setAlias Phar::setAlias ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.2.1) Phar::setAlias — Set the alias for the Phar archive ### Description ``` public Phar::setAlias(string $alias): bool ``` > > **Note**: > > > This method requires the php.ini setting `phar.readonly` to be set to `0` in order to work for [Phar](class.phar) objects. Otherwise, a [PharException](class.pharexception) will be thrown. > > > Set the alias for the Phar archive, and write it as the permanent alias for this phar archive. An alias can be used internally to a phar archive to ensure that use of the `phar` stream wrapper to access internal files always works regardless of the location of the phar archive on the filesystem. Another alternative is to rely upon Phar's interception of [include](function.include) or to use [Phar::interceptFileFuncs()](phar.interceptfilefuncs) and use relative paths. ### Parameters `alias` A shorthand string that this archive can be referred to in `phar` stream wrapper access. ### Return Values ### Errors/Exceptions Throws [UnexpectedValueException](class.unexpectedvalueexception) when write access is disabled, and [PharException](class.pharexception) if the alias is already in use or any problems were encountered flushing changes to disk. ### Examples **Example #1 A **Phar::setAlias()** example** ``` <?php try {     $phar = new Phar('myphar.phar');     $phar->setAlias('myp.phar'); } catch (Exception $e) {     // handle error } ?> ``` ### See Also * [Phar::\_\_construct()](phar.construct) - Construct a Phar archive object * [Phar::interceptFileFuncs()](phar.interceptfilefuncs) - Instructs phar to intercept fopen, file\_get\_contents, opendir, and all of the stat-related functions php image_type_to_extension image\_type\_to\_extension ========================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) image\_type\_to\_extension — Get file extension for image type ### Description ``` image_type_to_extension(int $image_type, bool $include_dot = true): string|false ``` Returns the extension for the given `IMAGETYPE_XXX` constant. ### Parameters `image_type` One of the `IMAGETYPE_XXX` constant. `include_dot` Whether to prepend a dot to the extension or not. Default to **`true`**. ### Return Values A string with the extension corresponding to the given image type, or **`false`** on failure. ### Examples **Example #1 **image\_type\_to\_extension()** example** ``` <?php // Create image instance $im = imagecreatetruecolor(100, 100); // Save image imagepng($im, './test' . image_type_to_extension(IMAGETYPE_PNG)); imagedestroy($im); ?> ``` ### Notes > > **Note**: > > > This function does not require the GD image library. > > > php XMLWriter::flush XMLWriter::flush ================ xmlwriter\_flush ================ (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 1.0.0) XMLWriter::flush -- xmlwriter\_flush — Flush current buffer ### Description Object-oriented style ``` public XMLWriter::flush(bool $empty = true): string|int ``` Procedural style ``` xmlwriter_flush(XMLWriter $writer, bool $empty = true): string|int ``` Flushes the current buffer. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `empty` Whether to empty the buffer or not. Default is **`true`**. ### Return Values If you opened the writer in memory, this function returns the generated XML buffer, Else, if using URI, this function will write the buffer and return the number of written bytes. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | | 8.0.0 | This function can no longer return **`false`**. | php xhprof_sample_disable xhprof\_sample\_disable ======================= (PECL xhprof >= 0.9.0) xhprof\_sample\_disable — Stops xhprof sample profiler ### Description ``` xhprof_sample_disable(): array ``` Stops the sample mode xhprof profiler, and ### Parameters This function has no parameters. ### Return Values An array of xhprof sample data, from the run. ### Examples **Example #1 **xhprof\_sample\_disable()** example** ``` <?php xhprof_sample_enable(); for ($i = 0; $i <= 10000; $i++) {     $a = strlen($i);     $b = $i * $a;     $c = rand(); } $xhprof_data = xhprof_sample_disable(); print_r($xhprof_data); ?> ``` The above example will output something similar to: ``` Array ( [1272935300.800000] => main() [1272935300.900000] => main() ) ``` php imagecolormatch imagecolormatch =============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) imagecolormatch — Makes the colors of the palette version of an image more closely match the true color version ### Description ``` imagecolormatch(GdImage $image1, GdImage $image2): bool ``` Makes the colors of the palette version of an image more closely match the true color version. ### Parameters `image1` A truecolor image object. `image2` A palette image object pointing to an image that has the same size as `image1`. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image1` and `image2` expect [GdImage](class.gdimage) instances now; previously, resources were expected. | ### Examples **Example #1 **imagecolormatch()** example** ``` <?php // Setup the true color and palette images $im1 = imagecreatefrompng('./gdlogo.png'); $im2 = imagecreate(imagesx($im1), imagesy($im1)); // Add some colors to $im2 $colors   = Array(); $colors[] = imagecolorallocate($im2, 255, 36, 74); $colors[] = imagecolorallocate($im2, 40, 0, 240); $colors[] = imagecolorallocate($im2, 82, 100, 255); $colors[] = imagecolorallocate($im2, 84, 63, 44); // Match these colors with the true color image imagecolormatch($im1, $im2); // Free from memory imagedestroy($im1); imagedestroy($im2); ?> ``` ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image php Yac::__set Yac::\_\_set ============ (PECL yac >= 1.0.0) Yac::\_\_set — Setter ### Description ``` public Yac::__set(string $keys, mixed $value): mixed ``` store a item into cache ### Parameters `keys` string key `value` mixed value, All php value type could be stored except [resource](language.types.resource) ### Return Values Always return the value self php fdf_add_doc_javascript fdf\_add\_doc\_javascript ========================= (PHP 4 >= 4.3.0, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_add\_doc\_javascript — Adds javascript code to the FDF document ### Description ``` fdf_add_doc_javascript(resource $fdf_document, string $script_name, string $script_code): bool ``` Adds a script to the FDF, which Acrobat then adds to the doc-level scripts of a document, once the FDF is imported into it. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `script_name` The script name. `script_code` The script code. It is strongly suggested to use `\r` for linebreaks within the script code. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Adding JavaScript code to a FDF** ``` <?php $fdf = fdf_create(); fdf_add_doc_javascript($fdf, "PlusOne", "function PlusOne(x)\r{\r  return x+1;\r}\r"); fdf_save($fdf); ?> ``` will create a FDF like this: ``` %FDF-1.2 %âãÏÓ 1 0 obj << /FDF << /JavaScript << /Doc [ (PlusOne)(function PlusOne\(x\)\r{\r return x+1;\r}\r)] >> >> >> endobj trailer << /Root 1 0 R >> %%EOF ``` php svn_fs_change_node_prop svn\_fs\_change\_node\_prop =========================== (PECL svn >= 0.2.0) svn\_fs\_change\_node\_prop — Return true if everything is ok, false otherwise ### Description ``` svn_fs_change_node_prop( resource $root, string $path, string $name, string $value ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Return true if everything is ok, false otherwise ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php SolrClient::setResponseWriter SolrClient::setResponseWriter ============================= (PECL solr >= 0.9.11) SolrClient::setResponseWriter — Sets the response writer used to prepare the response from Solr ### Description ``` public SolrClient::setResponseWriter(string $responseWriter): void ``` Sets the response writer used to prepare the response from Solr ### Parameters `responseWriter` One of the following: * `json` * `phps` * `xml` ### Return Values No value is returned. ### Examples **Example #1 **SolrClient::setResponseWriter()** example** ``` <?php // This is my custom class for objects class SolrClass {    public $_properties = array();    public function __get($property_name) {              if (property_exists($this, $property_name)) {                  return $this->$property_name;              } else if (isset($_properties[$property_name])) {                  return $_properties[$property_name];       }              return null;    } } $options = array (   'hostname' => 'localhost',   'port' => 8983,   'path' => '/solr/core1' ); $client = new SolrClient($options); $client->setResponseWriter("json"); //$response = $client->ping(); $query = new SolrQuery(); $query->setQuery("*:*"); $query->set("objectClassName", "SolrClass"); $query->set("objectPropertiesStorageMode", 1); // 0 for independent properties, 1 for combined try { $response = $client->query($query); $resp = $response->getResponse(); print_r($response); print_r($resp); } catch (Exception $e) { print_r($e); } ?> ``` php IntlRuleBasedBreakIterator::getRuleStatus IntlRuleBasedBreakIterator::getRuleStatus ========================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlRuleBasedBreakIterator::getRuleStatus — Get the largest status value from the break rules that determined the current break position ### Description ``` public IntlRuleBasedBreakIterator::getRuleStatus(): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php gzrewind gzrewind ======== (PHP 4, PHP 5, PHP 7, PHP 8) gzrewind — Rewind the position of a gz-file pointer ### Description ``` gzrewind(resource $stream): bool ``` Sets the file position indicator of the given gz-file pointer to the beginning of the file stream. ### Parameters `stream` The gz-file pointer. It must be valid, and must point to a file successfully opened by [gzopen()](function.gzopen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [gzseek()](function.gzseek) - Seek on a gz-file pointer * [gztell()](function.gztell) - Tell gz-file pointer read/write position php Parle\Parser::trace Parle\Parser::trace =================== (PECL parle >= 0.5.1) Parle\Parser::trace — Trace the parser operation ### Description ``` public Parle\Parser::trace(): string ``` Retrieve the current parser operation description. This can be especially useful for studying the parser and to optimize the grammar. ### Parameters This function has no parameters. ### Return Values Returns a string with the trace information. php Ds\Deque::first Ds\Deque::first =============== (PECL ds >= 1.0.0) Ds\Deque::first — Returns the first value in the deque ### Description ``` public Ds\Deque::first(): mixed ``` Returns the first value in the deque. ### Parameters This function has no parameters. ### Return Values The first value in the deque. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Deque::first()** example** ``` <?php $deque = new \Ds\Deque([1, 2, 3]); var_dump($deque->first()); ?> ``` The above example will output something similar to: ``` int(1) ``` php SolrQuery::getGroup SolrQuery::getGroup =================== (PECL solr >= 2.2.0) SolrQuery::getGroup — Returns true if grouping is enabled ### Description ``` public SolrQuery::getGroup(): bool ``` Returns true if grouping is enabled ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter) php ReflectionClass::getMethod ReflectionClass::getMethod ========================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getMethod — Gets a [ReflectionMethod](class.reflectionmethod) for a class method ### Description ``` public ReflectionClass::getMethod(string $name): ReflectionMethod ``` Gets a [ReflectionMethod](class.reflectionmethod) for a class method. ### Parameters `name` The method name to reflect. ### Return Values A [ReflectionMethod](class.reflectionmethod). ### Errors/Exceptions A [ReflectionException](class.reflectionexception) if the method does not exist. ### Examples **Example #1 Basic usage of **ReflectionClass::getMethod()**** ``` <?php $class = new ReflectionClass('ReflectionClass'); $method = $class->getMethod('getMethod'); var_dump($method); ?> ``` The above example will output: ``` object(ReflectionMethod)#2 (2) { ["name"]=> string(9) "getMethod" ["class"]=> string(15) "ReflectionClass" } ``` ### See Also * [ReflectionClass::getMethods()](reflectionclass.getmethods) - Gets an array of methods php Yaf_Application::getConfig Yaf\_Application::getConfig =========================== (Yaf >=1.0.0) Yaf\_Application::getConfig — Retrive the config instance ### Description ``` public Yaf_Application::getConfig(): Yaf_Config_Abstract ``` ### Parameters This function has no parameters. ### Return Values A [Yaf\_Config\_Abstract](class.yaf-config-abstract) instance ### Examples **Example #1 **Yaf\_Application::getConfig()**example** ``` <?php $config = array(     "application" => array(         "directory" => realpath(dirname(__FILE__)) . "/application",     ), ); /** Yaf_Application */ $application = new Yaf_Application($config); print_r($application->getConfig()); ?> ``` The above example will output something similar to: ``` Yaf_Config_Simple Object ( [_config:protected] => Array ( [application] => Array ( [directory] => /home/laruence/local/www/htdocs/application ) ) [_readonly:protected] => 1 ) ``` php Imagick::radialBlurImage Imagick::radialBlurImage ======================== (PECL imagick 2, PECL imagick 3) Imagick::radialBlurImage — Radial blurs an image **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::radialBlurImage(float $angle, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Radial blurs an image. ### Parameters `angle` `channel` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::radialBlurImage()**** ``` <?php function radialBlurImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     //Blur 3 times with different radii     $imagick->radialBlurImage(3);     $imagick->radialBlurImage(5);     $imagick->radialBlurImage(7);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php eio_seek eio\_seek ========= (PECL eio >= 0.5.0b) eio\_seek — Repositions the offset of the open file associated with the `fd` argument to the argument `offset` according to the directive `whence` ### Description ``` eio_seek( mixed $fd, int $offset, int $whence, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_seek()** repositions the offset of the open file associated with stream, Socket resource, or file descriptor specified by `fd` to the argument `offset` according to the directive `whence` as follows: * **`EIO_SEEK_SET`** - Set position equal to `offset` bytes. * **`EIO_SEEK_CUR`** - Set position to current location plus `offset`. * **`EIO_SEEK_END`** - Set position to end-of-file plus `offset`. ### Parameters `fd` Stream, Socket resource, or numeric file descriptor `offset` Starting point from which data is to be read. `length` Number of bytes to be read. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_seek()** returns request resource on success, or **`false`** on failure. php IntlCalendar::setLenient IntlCalendar::setLenient ======================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::setLenient — Set whether date/time interpretation is to be lenient ### Description Object-oriented style ``` public IntlCalendar::setLenient(bool $lenient): bool ``` Procedural style ``` intlcal_set_lenient(IntlCalendar $calendar, bool $lenient): bool ``` Defines whether the calendar is ‘lenient mode’. In such a mode, some of out-of-bounds values for some fields are accepted, the behavior being similar to that of [IntlCalendar::add()](intlcalendar.add) (i.e., the value wraps around, carrying into more significant fields each time). If the lenient mode is off, then such values will generate an error. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `lenient` Use **`true`** to activate the lenient mode; **`false`** otherwise. ### Return Values Always returns **`true`**. ### Examples See the example in [IntlCalendar::isLenient()](intlcalendar.islenient). php gnupg_cleardecryptkeys gnupg\_cleardecryptkeys ======================= (PECL gnupg >= 0.5) gnupg\_cleardecryptkeys — Removes all keys which were set for decryption before ### Description ``` gnupg_cleardecryptkeys(resource $identifier): bool ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Procedural **gnupg\_cleardecryptkeys()** example** ``` <?php $res = gnupg_init(); gnupg_cleardecryptkeys($res); ?> ``` **Example #2 OO **gnupg\_cleardecryptkeys()** example** ``` <?php $gpg = new gnupg(); $gpg->cleardecryptkeys(); ?> ```
programming_docs
php ReflectionClass::isSubclassOf ReflectionClass::isSubclassOf ============================= (PHP 5, PHP 7, PHP 8) ReflectionClass::isSubclassOf — Checks if a subclass ### Description ``` public ReflectionClass::isSubclassOf(ReflectionClass|string $class): bool ``` Checks if the class is a subclass of a specified class or implements a specified interface. ### Parameters `class` Either the name of the class as string or a [ReflectionClass](class.reflectionclass) object of the class to check against. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ReflectionClass::isInterface()](reflectionclass.isinterface) - Checks if the class is an interface * [ReflectionClass::implementsInterface()](reflectionclass.implementsinterface) - Implements interface * [is\_subclass\_of()](function.is-subclass-of) - Checks if the object has this class as one of its parents or implements it * [get\_parent\_class()](function.get-parent-class) - Retrieves the parent class name for object or class php svn_repos_fs_begin_txn_for_commit svn\_repos\_fs\_begin\_txn\_for\_commit ======================================= (PECL svn >= 0.2.0) svn\_repos\_fs\_begin\_txn\_for\_commit — Create a new transaction ### Description ``` svn_repos_fs_begin_txn_for_commit( resource $repos, int $rev, string $author, string $log_msg ): resource ``` **Warning**This function is currently not documented; only its argument list is available. Create a new transaction ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php XMLWriter::endDtd XMLWriter::endDtd ================= xmlwriter\_end\_dtd =================== (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::endDtd -- xmlwriter\_end\_dtd — End current DTD ### Description Object-oriented style ``` public XMLWriter::endDtd(): bool ``` Procedural style ``` xmlwriter_end_dtd(XMLWriter $writer): bool ``` Ends the DTD of the document. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::startDtd()](xmlwriter.startdtd) - Create start DTD tag * [XMLWriter::writeDtd()](xmlwriter.writedtd) - Write full DTD tag php fsync fsync ===== (PHP 8 >= 8.1.0) fsync — Synchronizes changes to the file (including meta-data) ### Description ``` fsync(resource $stream): bool ``` This function synchronizes changes to the file, including its meta-data. This is similar to [fflush()](function.fflush), but it also instructs the operating system to write to the storage media. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **fsync()** example** ``` <?php $file = 'test.txt'; $stream = fopen($file, 'w'); fwrite($stream, 'test data'); fwrite($stream, "\r\n"); fwrite($stream, 'additional data'); fsync($stream); fclose($stream); ?> ``` ### See Also * [fdatasync()](function.fdatasync) - Synchronizes data (but not meta-data) to the file * [fflush()](function.fflush) - Flushes the output to a file php The UnderflowException class The UnderflowException class ============================ Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Exception thrown when performing an invalid operation on an empty container, such as removing an element. Class synopsis -------------- class **UnderflowException** extends [RuntimeException](class.runtimeexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php imap_renamemailbox imap\_renamemailbox =================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_renamemailbox — Rename an old mailbox to new mailbox ### Description ``` imap_renamemailbox(IMAP\Connection $imap, string $from, string $to): bool ``` This function renames on old mailbox to new mailbox (see [imap\_open()](function.imap-open) for the format of `mbox` names). ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `from` The old mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `to` The new mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_createmailbox()](function.imap-createmailbox) - Create a new mailbox * [imap\_deletemailbox()](function.imap-deletemailbox) - Delete a mailbox php uopz_add_function uopz\_add\_function =================== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_add\_function — Adds non-existent function or method ### Description ``` uopz_add_function(string $function, Closure $handler, int &$flags = ZEND_ACC_PUBLIC): bool ``` ``` uopz_add_function( string $class, string $function, Closure $handler, int &$flags = ZEND_ACC_PUBLIC, int &$all = true ): bool ``` Adds a non-existent function or method. ### Parameters `class` The name of the class. `function` The name of the function or method. `handler` The [Closure](class.closure) that defines the new function or method. `flags` Flags to set for the new function or method. `all` Whether all classes that descend from `class` will also be affected. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions **uopz\_add\_function()** throws a [RuntimeException](class.runtimeexception) if the function or method to add already exists. ### Examples **Example #1 Basic **uopz\_add\_function()** Usage** ``` <?php uopz_add_function('foo', function () {echo 'bar';}); foo(); ?> ``` The above example will output: ``` bar ``` ### See Also * [uopz\_del\_function()](function.uopz-del-function) - Deletes previously added function or method * [uopz\_set\_return()](function.uopz-set-return) - Provide a return value for an existing function php DOMNode::normalize DOMNode::normalize ================== (PHP 5, PHP 7, PHP 8) DOMNode::normalize — Normalizes the node ### Description ``` public DOMNode::normalize(): void ``` Remove empty text nodes and merge adjacent text nodes in this node and all its children. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [» The DOM Specification](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-normalize) * [DOMDocument::normalizeDocument()](domdocument.normalizedocument) - Normalizes the document php lzf_optimized_for lzf\_optimized\_for =================== (PECL lzf >= 1.0.0) lzf\_optimized\_for — Determines what LZF extension was optimized for ### Description ``` lzf_optimized_for(): int ``` Determines what was LZF extension optimized for during compilation. ### Parameters This function has no parameters. ### Return Values Returns 1 if LZF was optimized for speed, 0 for compression. php ftell ftell ===== (PHP 4, PHP 5, PHP 7, PHP 8) ftell — Returns the current position of the file read/write pointer ### Description ``` ftell(resource $stream): int|false ``` Returns the position of the file pointer referenced by `stream`. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [popen()](function.popen). **ftell()** gives undefined results for append-only streams (opened with "a" flag). ### Return Values Returns the position of the file pointer referenced by `stream` as an integer; i.e., its offset into the file stream. If an error occurs, returns **`false`**. > **Note**: Because PHP's integer type is signed and many platforms use 32bit integers, some filesystem functions may return unexpected results for files which are larger than 2GB. > > ### Examples **Example #1 **ftell()** example** ``` <?php // opens a file and read some data $fp = fopen("/etc/passwd", "r"); $data = fgets($fp, 12); // where are we ? echo ftell($fp); // 11 fclose($fp); ?> ``` ### See Also * [fopen()](function.fopen) - Opens file or URL * [popen()](function.popen) - Opens process file pointer * [fseek()](function.fseek) - Seeks on a file pointer * [rewind()](function.rewind) - Rewind the position of a file pointer php pg_lo_close pg\_lo\_close ============= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_close — Close a large object ### Description ``` pg_lo_close(PgSql\Lob $lob): bool ``` **pg\_lo\_close()** closes a large object. To use the large object interface, it is necessary to enclose it within a transaction block. > > **Note**: > > > This function used to be called **pg\_loclose()**. > > ### Parameters `lob` An [PgSql\Lob](class.pgsql-lob) instance, returned by [pg\_lo\_open()](function.pg-lo-open). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `lob` parameter expects an [PgSql\Lob](class.pgsql-lob) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_close()** example** ``` <?php    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $oid = pg_lo_create($database);    echo "$oid\n";    $handle = pg_lo_open($database, $oid, "w");    echo "$handle\n";    pg_lo_write($handle, "large object data");    pg_lo_close($handle);    pg_query($database, "commit"); ?> ``` ### See Also * [pg\_lo\_open()](function.pg-lo-open) - Open a large object * [pg\_lo\_create()](function.pg-lo-create) - Create a large object * [pg\_lo\_import()](function.pg-lo-import) - Import a large object from file php Yaf_Loader::setLibraryPath Yaf\_Loader::setLibraryPath =========================== (Yaf >=2.1.4) Yaf\_Loader::setLibraryPath — Change the library path ### Description ``` public Yaf_Loader::setLibraryPath(string $directory, bool $is_global = false): Yaf_Loader ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php SplDoublyLinkedList::current SplDoublyLinkedList::current ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::current — Return current array entry ### Description ``` public SplDoublyLinkedList::current(): mixed ``` Get the current doubly linked list node. ### Parameters This function has no parameters. ### Return Values The current node value. php date_timestamp_get date\_timestamp\_get ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) date\_timestamp\_get — Alias of [DateTime::getTimestamp()](datetime.gettimestamp) ### Description This function is an alias of: [DateTime::getTimestamp()](datetime.gettimestamp) php socket_cmsg_space socket\_cmsg\_space =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) socket\_cmsg\_space — Calculate message buffer size ### Description ``` socket_cmsg_space(int $level, int $type, int $num = 0): ?int ``` Calculates the size of the buffer that should be allocated for receiving the ancillary data. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `level` `type` ### Return Values ### See Also * [socket\_recvmsg()](function.socket-recvmsg) - Read a message * [socket\_sendmsg()](function.socket-sendmsg) - Send a message php DateTimeImmutable::createFromFormat DateTimeImmutable::createFromFormat =================================== date\_create\_immutable\_from\_format ===================================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) DateTimeImmutable::createFromFormat -- date\_create\_immutable\_from\_format — Parses a time string according to a specified format ### Description Object-oriented style ``` public static DateTimeImmutable::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false ``` Procedural style ``` date_create_immutable_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTimeImmutable|false ``` Returns a new DateTimeImmutable object representing the date and time specified by the `datetime` string, which was formatted in the given `format`. ### Parameters `format` The format that the passed in string should be in. See the formatting options below. In most cases, the same letters as for the [date()](function.date) can be used. All fields are initialised with the current date/time. In most cases you would want to reset these to "zero" (the Unix epoch, `1970-01-01 00:00:00 UTC`). You do that by including the `!` character as first character in your `format`, or `|` as your last. Please see the documentation for each character below for more information. The format is parsed from left to right, which means that in some situations the order in which the format characters are present affects the result. In the case of `z` (the day of the year), it is required that a year has already been parsed, for example through the `Y` or `y` characters. Letters that are used for parsing numbers allow a wide range of values, outside of what the logical range would be. For example, the `d` (day of the month) accepts values in the range from `00` to `99`. The only constraint is on the amount of digits. The date/time parser's overflow mechanism is used when out-of-range values are given. The examples below show some of this behaviour. This also means that the data parsed for a format letter is greedy, and will read up to the amount of digits its format allows for. That can then also mean that there are no longer enough characters in the `datetime` string for following format characters. An example on this page also illustrates this issue. **The following characters are recognized in the `format` parameter string**| `format` character | Description | Example parsable values | | --- | --- | --- | | *Day* | --- | --- | | `d` and `j` | Day of the month, 2 digits with or without leading zeros | `01` to `31` or `1` to `31`. (2 digit numbers higher than the number of days in the month are accepted, in which case they will make the month overflow. For example using 33 with January, means February 2nd) | | `D` and `l` | A textual representation of a day | `Mon` through `Sun` or `Sunday` through `Saturday`. If the day name given is different then the day name belonging to a parsed (or default) date is different, then an overflow occurs to the *next* date with the given day name. See the examples below for an explanation. | | `S` | English ordinal suffix for the day of the month, 2 characters. It's ignored while processing. | `st`, `nd`, `rd` or `th`. | | `z` | The day of the year (starting from 0); must be preceded by `Y` or `y`. | `0` through `365`. (3 digit numbers higher than the numbers in a year are accepted, in which case they will make the year overflow. For example using 366 with 2022, means January 2nd, 2023) | | *Month* | --- | --- | | `F` and `M` | A textual representation of a month, such as January or Sept | `January` through `December` or `Jan` through `Dec` | | `m` and `n` | Numeric representation of a month, with or without leading zeros | `01` through `12` or `1` through `12`. (2 digit numbers higher than 12 are accepted, in which case they will make the year overflow. For example using 13 means January in the next year) | | *Year* | --- | --- | | `X` and `x` | A full numeric representation of a year, up to 19 digits, optionally prefixed by `+` or `-` | Examples: `0055`, `787`, `1999`, `-2003`, `+10191` | | `Y` | A full numeric representation of a year, up to 4 digits | Examples: `0055`, `787`, `1999`, `2003` | | `y` | A two digit representation of a year (which is assumed to be in the range 1970-2069, inclusive) | Examples: `99` or `03` (which will be interpreted as `1999` and `2003`, respectively) | | *Time* | --- | --- | | `a` and `A` | Ante meridiem and Post meridiem | `am` or `pm` | | `g` and `h` | 12-hour format of an hour with or without leading zero | `1` through `12` or `01` through `12` (2 digit numbers higher than 12 are accepted, in which case they will make the day overflow. For example using `14` means `02` in the next AM/PM period) | | `G` and `H` | 24-hour format of an hour with or without leading zeros | `0` through `23` or `00` through `23` (2 digit numbers higher than 24 are accepted, in which case they will make the day overflow. For example using `26` means `02:00` the next day) | | `i` | Minutes with leading zeros | `00` to `59`. (2 digit numbers higher than 59 are accepted, in which case they will make the hour overflow. For example using `66` means `:06` the next hour) | | `s` | Seconds, with leading zeros | `00` through `59` (2 digit numbers higher than 59 are accepted, in which case they will make the minute overflow. For example using `90` means `:30` the next minute) | | `v` | Fraction in milliseconds (up to three digits) | Example: `12` (`0.12` seconds), `345` (`0.345` seconds) | | `u` | Fraction in microseconds (up to six digits) | Example: `45` (`0.45` seconds), `654321` (`0.654321` seconds) | | *Timezone* | --- | --- | | `e`, `O`, `P` and `T` | Timezone identifier, or difference to UTC in hours, or difference to UTC with colon between hours and minutes, or timezone abbreviation | Examples: `UTC`, `GMT`, `Atlantic/Azores` or `+0200` or `+02:00` or `EST`, `MDT` | | *Full Date/Time* | --- | --- | | `U` | Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) | Example: `1292177455` | | *Whitespace and Separators* | --- | --- | | (space) | One space or one tab | Example: | | `#` | One of the following separation symbol: `;`, `:`, `/`, `.`, `,`, `-`, `(` or `)` | Example: `/` | | `;`, `:`, `/`, `.`, `,`, `-`, `(` or `)` | The specified character. | Example: `-` | | `?` | A random byte | Example: `^` (Be aware that for UTF-8 characters you might need more than one `?`. In this case, using `*` is probably what you want instead) | | `*` | Random bytes until the next separator or digit | Example: `*` in `Y-*-d` with the string `2009-aWord-08` will match `aWord` | | `!` | Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values ( `0` for hour, minute, second and fraction, `1` for month and day, `1970` for year and `UTC` for timezone information) | Without `!,` all fields will be set to the current date and time. | | `|` | Resets all fields (year, month, day, hour, minute, second, fraction and timezone information) to zero-like values if they have not been parsed yet | `Y-m-d|` will set the year, month and day to the information found in the string to parse, and sets the hour, minute and second to 0. | | `+` | If this format specifier is present, trailing data in the string will not cause an error, but a warning instead | Use [DateTimeImmutable::getLastErrors()](datetimeimmutable.getlasterrors) to find out whether trailing data was present. | Unrecognized characters in the format string will cause the parsing to fail and an error message is appended to the returned structure. You can query error messages with [DateTimeImmutable::getLastErrors()](datetimeimmutable.getlasterrors). To include literal characters in `format`, you have to escape them with a backslash (`\`). If `format` does not contain the character `!` then portions of the generated date/time which are not specified in `format` will be set to the current system time. If `format` contains the character `!`, then portions of the generated date/time not provided in `format`, as well as values to the left-hand side of the `!`, will be set to corresponding values from the Unix epoch. If any time character is parsed, then all other time-related fields are set to "0", unless also parsed. The Unix epoch is 1970-01-01 00:00:00 UTC. `datetime` String representing the time. `timezone` A [DateTimeZone](class.datetimezone) object representing the desired time zone. If `timezone` is omitted or **`null`** and `datetime` contains no timezone, the current timezone will be used. > > **Note**: > > > The `timezone` parameter and the current timezone are ignored when the `datetime` parameter either contains a UNIX timestamp (e.g. `946684800`) or specifies a timezone (e.g. `2010-01-28T15:00:00+02:00`). > > ### Return Values Returns a new DateTimeImmutable instance or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | The `X` and `x` `format` specifiers have been added. | | 7.3.0 | The `v` `format` specifier has been added. | ### Examples **Example #1 **DateTimeImmutable::createFromFormat()** example** Object-oriented style ``` <?php $date = DateTimeImmutable::createFromFormat('j-M-Y', '15-Feb-2009'); echo $date->format('Y-m-d'); ?> ``` **Example #2 Intricacies of **DateTimeImmutable::createFromFormat()**** ``` <?php echo 'Current time: ' . date('Y-m-d H:i:s') . "\n"; $format = 'Y-m-d'; $date = DateTimeImmutable::createFromFormat($format, '2009-02-15'); echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n"; $format = 'Y-m-d H:i:s'; $date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17'); echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n"; $format = 'Y-m-!d H:i:s'; $date = DateTimeImmutable::createFromFormat($format, '2009-02-15 15:16:17'); echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n"; $format = '!d'; $date = DateTimeImmutable::createFromFormat($format, '15'); echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n"; $format = 'i'; $date = DateTimeImmutable::createFromFormat($format, '15'); echo "Format: $format; " . $date->format('Y-m-d H:i:s') . "\n"; ?> ``` The above example will output something similar to: ``` Current time: 2022-06-02 15:50:46 Format: Y-m-d; 2009-02-15 15:50:46 Format: Y-m-d H:i:s; 2009-02-15 15:16:17 Format: Y-m-!d H:i:s; 1970-01-15 15:16:17 Format: !d; 1970-01-15 00:00:00 Format: i; 2022-06-02 00:15:00 ``` **Example #3 Format string with literal characters** ``` <?php echo DateTimeImmutable::createFromFormat('H\h i\m s\s','23h 15m 03s')->format('H:i:s'); ?> ``` The above example will output something similar to: ``` 23:15:03 ``` **Example #4 Overflow behaviour** ``` <?php echo DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97')->format(DateTimeImmutable::RFC2822); ?> ``` The above example will output something similar to: ``` Sat, 04 Jun 2022 17:01:37 +0000 ``` Although the result looks odd, it is correct, as the following overflows happen: 1. `97` seconds overflows to `1` minute, leaving `37` seconds. 2. `61` minutes overflows to `1` hour, leaving `1` minutes. 3. `35` days overflows to `1` month, leaving `4` days. The amount of days that are left over depends on the month, as not every month has the same amount of days. 4. `18` months overflows to `1` year, leaving `6` months. **Example #5 Overflowing day name behaviour** ``` <?php $d = DateTime::createFromFormat(DateTimeInterface::RFC1123, 'Mon, 3 Aug 2020 25:00:00 +0000'); echo $d->format(DateTime::RFC1123), "\n"; ?> ``` The above example will output something similar to: ``` Mon, 10 Aug 2020 01:00:00 +0000 ``` Although the result looks odd, it is correct, as the following overflows happen: 1. `3 Aug 2020 25:00:00` overflows to `(Tue) 4 Aug 2020 01:00`. 2. `Mon` gets applied, which advances the date to `Mon, 10 Aug 2020 01:00:00`. The explanation of relative keywords such as `Mon` is explained in the section on [relative formats](https://www.php.net/manual/en/datetime.formats.relative.php). In order to detect overflows in dates, you can use the [DateTimeImmutable::getLastErrors()](datetimeimmutable.getlasterrors) name, which will include a warning if an overflow occured. **Example #6 Detecting overflown dates** ``` <?php $d = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', '2021-17-35 16:60:97'); echo $d->format(DateTimeImmutable::RFC2822), "\n\n"; var_dump(DateTimeImmutable::GetLastErrors()); ?> ``` The above example will output something similar to: ``` Sat, 04 Jun 2022 17:01:37 +0000 array(4) { 'warning_count' => int(2) 'warnings' => array(1) { [19] => string(27) "The parsed date was invalid" } 'error_count' => int(0) 'errors' => array(0) { } } ``` **Example #7 Greedy parsing behaviour** ``` <?php print_r(date_parse_from_format('Gis', '60101')); ?> ``` The above example will output something similar to: ``` Array ( [year] => [month] => [day] => [hour] => 60 [minute] => 10 [second] => 0 [fraction] => 0 [warning_count] => 1 [warnings] => Array ( [5] => The parsed time was invalid ) [error_count] => 1 [errors] => Array ( [4] => A two digit second could not be found ) [is_localtime] => ) ``` The `G` format is to parse 24 hour clock hours, with or without leading zero. This requires to parse 1 or 2 digits. Because there are two following digits, it greedily reads this as `60`. The following `i` and `s` format characters both require two digits. This means that `10` is passed as minute (`i`), and that there are then not enough digits left to parse for as second (`s`). The `errors` array indicates this problem. Additionally, an hour of `60` is outside the range `0`-`24`, which causes the `warnings` array to include a warning that the time is invalid. ### See Also * [DateTimeImmutable::\_\_construct()](datetimeimmutable.construct) - Returns new DateTimeImmutable object * [DateTimeImmutable::getLastErrors()](datetimeimmutable.getlasterrors) - Returns the warnings and errors * [checkdate()](function.checkdate) - Validate a Gregorian date * [strptime()](function.strptime) - Parse a time/date generated with strftime
programming_docs
php svn_fs_is_file svn\_fs\_is\_file ================= (PECL svn >= 0.2.0) svn\_fs\_is\_file — Determines if a path points to a file ### Description ``` svn_fs_is_file(resource $root, string $path): bool ``` **Warning**This function is currently not documented; only its argument list is available. Determines if the given path points to a file. ### Parameters `root` `path` ### Return Values Returns **`true`** if the path points to a file, **`false`** otherwise. ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php ImagickDraw::pathEllipticArcRelative ImagickDraw::pathEllipticArcRelative ==================================== (PECL imagick 2, PECL imagick 3) ImagickDraw::pathEllipticArcRelative — Draws an elliptical arc ### Description ``` public ImagickDraw::pathEllipticArcRelative( float $rx, float $ry, float $x_axis_rotation, bool $large_arc_flag, bool $sweep_flag, float $x, float $y ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws an elliptical arc from the current point to (x, y) using relative coordinates. The size and orientation of the ellipse are defined by two radii (rx, ry) and an xAxisRotation, which indicates how the ellipse as a whole is rotated relative to the current coordinate system. The center (cx, cy) of the ellipse is calculated automatically to satisfy the constraints imposed by the other parameters. largeArcFlag and sweepFlag contribute to the automatic calculations and help determine how the arc is drawn. If `large_arc_flag` is **`true`** then draw the larger of the available arcs. If `sweep_flag` is true, then draw the arc matching a clock-wise rotation. ### Parameters `rx` x radius `ry` y radius `x_axis_rotation` x axis rotation `large_arc_flag` large arc flag `sweep_flag` sweep flag `x` x coordinate `y` y coordinate ### Return Values No value is returned. php checkdate checkdate ========= (PHP 4, PHP 5, PHP 7, PHP 8) checkdate — Validate a Gregorian date ### Description ``` checkdate(int $month, int $day, int $year): bool ``` Checks the validity of the date formed by the arguments. A date is considered valid if each parameter is properly defined. ### Parameters `month` The month is between 1 and 12 inclusive. `day` The day is within the allowed number of days for the given `month`. Leap `year`s are taken into consideration. `year` The year is between 1 and 32767 inclusive. ### Return Values Returns **`true`** if the date given is valid; otherwise returns **`false`**. ### Examples **Example #1 **checkdate()** example** ``` <?php var_dump(checkdate(12, 31, 2000)); var_dump(checkdate(2, 29, 2001)); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [mktime()](function.mktime) - Get Unix timestamp for a date * [strtotime()](function.strtotime) - Parse about any English textual datetime description into a Unix timestamp php delete delete ====== delete — See [unlink()](function.unlink) or [unset()](function.unset) ### Description There is no delete keyword or function in the PHP language. If you arrived at this page seeking to delete a file, try [unlink()](function.unlink). To delete a variable from the local scope, check out [unset()](function.unset). ### See Also * [unlink()](function.unlink) - Deletes a file * [unset()](function.unset) - Unset a given variable php FilesystemIterator::getFlags FilesystemIterator::getFlags ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) FilesystemIterator::getFlags — Get the handling flags ### Description ``` public FilesystemIterator::getFlags(): int ``` Gets the handling flags, as set in [FilesystemIterator::\_\_construct()](filesystemiterator.construct) or [FilesystemIterator::setFlags()](filesystemiterator.setflags). ### Parameters This function has no parameters. ### Return Values The integer value of the set flags. ### See Also * [FilesystemIterator::\_\_construct()](filesystemiterator.construct) - Constructs a new filesystem iterator * [FilesystemIterator::setFlags()](filesystemiterator.setflags) - Sets handling flags php Imagick::rotateImage Imagick::rotateImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::rotateImage — Rotates an image ### Description ``` public Imagick::rotateImage(mixed $background, float $degrees): bool ``` Rotates an image the specified number of degrees. Empty triangles left over from rotating the image are filled with the background color. ### Parameters `background` The background color `degrees` Rotation angle, in degrees. The rotation angle is interpreted as the number of degrees to rotate the image clockwise. ### Return Values Returns **`true`** on success. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object. | ### Examples **Example #1 **Imagick::rotateImage()**** ``` <?php function rotateImage($imagePath, $angle, $color) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->rotateimage($color, $angle);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php SolrQuery::getRows SolrQuery::getRows ================== (PECL solr >= 0.9.2) SolrQuery::getRows — Returns the maximum number of documents ### Description ``` public SolrQuery::getRows(): int ``` Returns the maximum number of documents from the complete result set to return to the client for every request ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php zlib_encode zlib\_encode ============ (PHP 5 >= 5.4.0, PHP 7, PHP 8) zlib\_encode — Compress data with the specified encoding ### Description ``` zlib_encode(string $data, int $encoding, int $level = -1): string|false ``` Compress data with the specified encoding. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `data` The data to compress. `encoding` The compression algorithm. Either **`ZLIB_ENCODING_RAW`**, **`ZLIB_ENCODING_DEFLATE`** or **`ZLIB_ENCODING_GZIP`**. `level` ### Return Values ### Examples **Example #1 **zlib\_encode()** example** ``` <?php $str = 'hello world'; $enc = zlib_encode($str, ZLIB_ENCODING_DEFLATE); echo bin2hex($enc); ?> ``` The above example will output: ``` 789ccb48cdc9c95728cf2fca4901001a0b045d ``` ### See Also * [zlib\_decode()](function.zlib-decode) - Uncompress any raw/gzip/zlib encoded data php WeakMap::offsetExists WeakMap::offsetExists ===================== (PHP 8) WeakMap::offsetExists — Checks whether a certain object is in the map ### Description ``` public WeakMap::offsetExists(object $object): bool ``` Checks whether the passed object is referenced in the map. ### Parameters `object` Object to check for. ### Return Values Returns **`true`** if the object is contained in the map, **`false`** otherwise. php array_uintersect_assoc array\_uintersect\_assoc ======================== (PHP 5, PHP 7, PHP 8) array\_uintersect\_assoc — Computes the intersection of arrays with additional index check, compares data by a callback function ### Description ``` array_uintersect_assoc(array $array, array ...$arrays, callable $value_compare_func): array ``` Computes the intersection of arrays with additional index check, compares data by a callback function. Note that the keys are used in the comparison unlike in [array\_uintersect()](function.array-uintersect). The data is compared by using a callback function. ### Parameters `array` The first array. `arrays` Arrays to compare against. `value_compare_func` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` ### Return Values Returns an array containing all the values of `array` that are present in all the arguments. ### Examples **Example #1 **array\_uintersect\_assoc()** example** ``` <?php $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); print_r(array_uintersect_assoc($array1, $array2, "strcasecmp")); ?> ``` The above example will output: ``` Array ( [a] => green ) ``` ### See Also * [array\_uintersect()](function.array-uintersect) - Computes the intersection of arrays, compares data by a callback function * [array\_intersect\_assoc()](function.array-intersect-assoc) - Computes the intersection of arrays with additional index check * [array\_intersect\_uassoc()](function.array-intersect-uassoc) - Computes the intersection of arrays with additional index check, compares indexes by a callback function * [array\_uintersect\_uassoc()](function.array-uintersect-uassoc) - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions php Parle\Lexer::advance Parle\Lexer::advance ==================== (PECL parle >= 0.5.1) Parle\Lexer::advance — Process next lexer rule ### Description ``` public Parle\Lexer::advance(): void ``` Processes the next rule and prepares the resulting token data. ### Parameters This function has no parameters. ### Return Values No value is returned. php readline_completion_function readline\_completion\_function ============================== (PHP 4, PHP 5, PHP 7, PHP 8) readline\_completion\_function — Registers a completion function ### Description ``` readline_completion_function(callable $callback): bool ``` This function registers a completion function. This is the same kind of functionality you'd get if you hit your tab key while using Bash. ### Parameters `callback` You must supply the name of an existing function which accepts a partial command line and returns an array of possible matches. ### Return Values Returns **`true`** on success or **`false`** on failure. php svn_blame svn\_blame ========== (PECL svn >= 0.3.0) svn\_blame — Get the SVN blame for a file ### Description ``` svn_blame(string $repository_url, int $revision_no = SVN_REVISION_HEAD): array ``` Get the SVN blame of a file from a repository URL. ### Parameters `repository_url` The repository URL. `revision_no` The revision number. ### Return Values An array of SVN blame information separated by line which includes the revision number, line number, line of code, author, and date. ### Examples **Example #1 **svn\_blame()** example** ``` <?php $svnurl = 'http://svn.example.org/svnroot/foo/trunk/index.php'; print_r( svn_blame($svnurl) ); ?> ``` The above example will output something similar to: ``` Array ( [0] = Array ( [rev] = 1 [line_no] = 1 [line] = Hello World [author] = joesmith [date] = 2007-07-02T05:51:26.628396Z ) [1] = Array ... ``` ### See Also * [svn\_diff()](function.svn-diff) - Recursively diffs two paths * **svn\_logs()** * [svn\_status()](function.svn-status) - Returns the status of working copy files and directories php SolrDocumentField::__destruct SolrDocumentField::\_\_destruct =============================== (PECL solr >= 0.9.2) SolrDocumentField::\_\_destruct — Destructor ### Description public **SolrDocumentField::\_\_destruct**() Destructor. ### Parameters This function has no parameters. ### Return Values None. php SolrDocument::rewind SolrDocument::rewind ==================== (PECL solr >= 0.9.2) SolrDocument::rewind — Resets the internal pointer to the beginning ### Description ``` public SolrDocument::rewind(): void ``` Resets the internal pointer to the beginning. ### Parameters This function has no parameters. ### Return Values This method has no return value. php fflush fflush ====== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) fflush — Flushes the output to a file ### Description ``` fflush(resource $stream): bool ``` This function forces a write of all buffered output to the resource pointed to by the file `stream`. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 File write example using **fflush()**** ``` <?php $filename = 'bar.txt'; $file = fopen($filename, 'r+'); rewind($file); fwrite($file, 'Foo'); fflush($file); ftruncate($file, ftell($file)); fclose($file); ?> ``` ### See Also * [clearstatcache()](function.clearstatcache) - Clears file status cache * [fwrite()](function.fwrite) - Binary-safe file write php frenchtojd frenchtojd ========== (PHP 4, PHP 5, PHP 7, PHP 8) frenchtojd — Converts a date from the French Republican Calendar to a Julian Day Count ### Description ``` frenchtojd(int $month, int $day, int $year): int ``` Converts a date from the French Republican Calendar to a Julian Day Count. These routines only convert dates in years 1 through 14 (Gregorian dates 22 September 1792 through 22 September 1806). This more than covers the period when the calendar was in use. ### Parameters `month` The month as a number from 1 (for Vendémiaire) to 13 (for the period of 5-6 days at the end of each year) `day` The day as a number from 1 to 30 `year` The year as a number between 1 and 14 ### Return Values The julian day for the given french revolution date as an integer. ### See Also * [jdtofrench()](function.jdtofrench) - Converts a Julian Day Count to the French Republican Calendar * [cal\_to\_jd()](function.cal-to-jd) - Converts from a supported calendar to Julian Day Count php Imagick::cropThumbnailImage Imagick::cropThumbnailImage =========================== (PECL imagick 2, PECL imagick 3) Imagick::cropThumbnailImage — Creates a crop thumbnail ### Description ``` public Imagick::cropThumbnailImage(int $width, int $height, bool $legacy = false): bool ``` Creates a fixed size thumbnail by first scaling the image up or down and cropping a specified area from the center. ### Parameters `width` The width of the thumbnail `height` The Height of the thumbnail ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php stream_wrapper_unregister stream\_wrapper\_unregister =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) stream\_wrapper\_unregister — Unregister a URL wrapper ### Description ``` stream_wrapper_unregister(string $protocol): bool ``` Allows you to disable an already defined stream wrapper. Once the wrapper has been disabled you may override it with a user-defined wrapper using [stream\_wrapper\_register()](function.stream-wrapper-register) or reenable it later on with [stream\_wrapper\_restore()](function.stream-wrapper-restore). ### Parameters `protocol` ### Return Values Returns **`true`** on success or **`false`** on failure. php array_walk array\_walk =========== (PHP 4, PHP 5, PHP 7, PHP 8) array\_walk — Apply a user supplied function to every member of an array ### Description ``` array_walk(array|object &$array, callable $callback, mixed $arg = null): bool ``` Applies the user-defined `callback` function to each element of the `array` array. **array\_walk()** is not affected by the internal array pointer of `array`. **array\_walk()** will walk through the entire array regardless of pointer position. ### Parameters `array` The input array. `callback` Typically, `callback` takes on two parameters. The `array` parameter's value being the first, and the key/index second. > > **Note**: > > > If `callback` needs to be working with the actual values of the array, specify the first parameter of `callback` as a [reference](https://www.php.net/manual/en/language.references.php). Then, any changes made to those elements will be made in the original array itself. > > > > **Note**: > > > Many internal functions (for example [strtolower()](function.strtolower)) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a `callback`. > > Only the values of the `array` may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable. `arg` If the optional `arg` parameter is supplied, it will be passed as the third parameter to the `callback`. ### Return Values Returns **`true`**. ### Errors/Exceptions As of PHP 7.1.0, an [ArgumentCountError](class.argumentcounterror) will be thrown if the `callback` function requires more than 2 parameters (the value and key of the array member), or more than 3 parameters if the `arg` is also passed. Previously, in this case an error of level [E\_WARNING](https://www.php.net/manual/en/errorfunc.constants.php) would be generated each time **array\_walk()** calls `callback`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | If `callback` expects the second or third parameter to be passed by reference, this function will now emit an **`E_WARNING`**. | ### Examples **Example #1 **array\_walk()** example** ``` <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); function test_alter(&$item1, $key, $prefix) {     $item1 = "$prefix: $item1"; } function test_print($item2, $key) {     echo "$key. $item2\n"; } echo "Before ...:\n"; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo "... and after:\n"; array_walk($fruits, 'test_print'); ?> ``` The above example will output: ``` Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple ``` **Example #2 **array\_walk()** example using anonymous function** ``` <?php $elements = ['a', 'b', 'c']; array_walk($elements, function ($value, $key) {   echo "{$key} => {$value}\n"; }); ?> ``` The above example will output: ``` 0 => a 1 => b 2 => c ``` ### See Also * [array\_walk\_recursive()](function.array-walk-recursive) - Apply a user function recursively to every member of an array * [iterator\_apply()](function.iterator-apply) - Call a function for every element in an iterator * [list()](function.list) - Assign variables as if they were an array * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor * [call\_user\_func\_array()](function.call-user-func-array) - Call a callback with an array of parameters * [array\_map()](function.array-map) - Applies the callback to the elements of the given arrays * [foreach](control-structures.foreach)
programming_docs
php Yaf_Config_Ini::__construct Yaf\_Config\_Ini::\_\_construct =============================== (Yaf >=1.0.0) Yaf\_Config\_Ini::\_\_construct — Yaf\_Config\_Ini constructor ### Description public **Yaf\_Config\_Ini::\_\_construct**(string `$config_file`, string `$section` = ?) [Yaf\_Config\_Ini](class.yaf-config-ini) constructor ### Parameters `config_file` path to an INI configure file `section` which section in that INI file you want to be parsed ### Return Values php Imagick::setImageMatteColor Imagick::setImageMatteColor =========================== (PECL imagick 2, PECL imagick 3) Imagick::setImageMatteColor — Sets the image matte color **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::setImageMatteColor(mixed $matte): bool ``` Sets the image matte color. ### Parameters `matte` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object. | php The CallbackFilterIterator class The CallbackFilterIterator class ================================ Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8) Class synopsis -------------- class **CallbackFilterIterator** extends [FilterIterator](class.filteriterator) { /\* Methods \*/ public [\_\_construct](callbackfilteriterator.construct)([Iterator](class.iterator) `$iterator`, [callable](language.types.callable) `$callback`) ``` public accept(): bool ``` /\* Inherited methods \*/ ``` public FilterIterator::accept(): bool ``` ``` public FilterIterator::current(): mixed ``` ``` public FilterIterator::getInnerIterator(): Iterator ``` ``` public FilterIterator::key(): mixed ``` ``` public FilterIterator::next(): void ``` ``` public FilterIterator::rewind(): void ``` ``` public FilterIterator::valid(): bool ``` ``` public IteratorIterator::current(): mixed ``` ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` ``` public IteratorIterator::key(): mixed ``` ``` public IteratorIterator::next(): void ``` ``` public IteratorIterator::rewind(): void ``` ``` public IteratorIterator::valid(): bool ``` } Examples -------- The callback should accept up to three arguments: the current item, the current key and the iterator, respectively. **Example #1 Available callback arguments** ``` <?php /**  * Callback for CallbackFilterIterator  *  * @param $current   Current item's value  * @param $key       Current item's key  * @param $iterator  Iterator being filtered  * @return boolean   TRUE to accept the current item, FALSE otherwise  */ function my_callback($current, $key, $iterator) {     // Your filtering code here } ?> ``` Any [callable](language.types.callable) may be used; such as a string containing a function name, an array for a method, or an anonymous function. **Example #2 Callback basic examples** ``` <?php $dir = new FilesystemIterator(__DIR__); // Filter large files ( > 100MB) function is_large_file($current) {     return $current->isFile() && $current->getSize() > 104857600; } $large_files = new CallbackFilterIterator($dir, 'is_large_file'); // Filter directories $files = new CallbackFilterIterator($dir, function ($current, $key, $iterator) {     return $current->isDir() && ! $iterator->isDot(); }); ?> ``` Table of Contents ----------------- * [CallbackFilterIterator::accept](callbackfilteriterator.accept) — Calls the callback with the current value, the current key and the inner iterator as arguments * [CallbackFilterIterator::\_\_construct](callbackfilteriterator.construct) — Create a filtered iterator from another iterator php ImagickPixel::clear ImagickPixel::clear =================== (PECL imagick 2, PECL imagick 3) ImagickPixel::clear — Clears resources associated with this object ### Description ``` public ImagickPixel::clear(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Clears the ImagickPixel object, leaving it in a fresh state. This also unsets any color associated with the object. ### Return Values Returns **`true`** on success. php __halt_compiler \_\_halt\_compiler ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) \_\_halt\_compiler — Halts the compiler execution ### Description ``` __halt_compiler(): void ``` Halts the execution of the compiler. This can be useful to embed data in PHP scripts, like the installation files. Byte position of the data start can be determined by the **`__COMPILER_HALT_OFFSET__`** constant which is defined only if there is a **\_\_halt\_compiler()** presented in the file. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 A **\_\_halt\_compiler()** example** ``` <?php // open this file $fp = fopen(__FILE__, 'r'); // seek file pointer to data fseek($fp, __COMPILER_HALT_OFFSET__); // and output it var_dump(stream_get_contents($fp)); // the end of the script execution __halt_compiler(); the installation data (eg. tar, gz, PHP, etc.) ``` ### Notes > > **Note**: > > > **\_\_halt\_compiler()** can only be used from the outermost scope. > > php Yaf_Request_Abstract::isHead Yaf\_Request\_Abstract::isHead ============================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::isHead — Determine if request is HEAD request ### Description ``` public Yaf_Request_Abstract::isHead(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean ### See Also * [Yaf\_Request\_Abstract::isGet()](yaf-request-abstract.isget) - Determine if request is GET request * [Yaf\_Request\_Abstract::isCli()](yaf-request-abstract.iscli) - Determine if request is CLI request * [Yaf\_Request\_Abstract::isPost()](yaf-request-abstract.ispost) - Determine if request is POST request * [Yaf\_Request\_Abstract::isPut()](yaf-request-abstract.isput) - Determine if request is PUT request * [Yaf\_Request\_Abstract::isOptions()](yaf-request-abstract.isoptions) - Determine if request is OPTIONS request * [Yaf\_Request\_Abstract::isXmlHTTPRequest()](yaf-request-abstract.isxmlhttprequest) - Determine if request is AJAX request php XMLWriter::startDtdEntity XMLWriter::startDtdEntity ========================= xmlwriter\_start\_dtd\_entity ============================= (PHP 5 >= 5.2.1, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::startDtdEntity -- xmlwriter\_start\_dtd\_entity — Create start DTD Entity ### Description Object-oriented style ``` public XMLWriter::startDtdEntity(string $name, bool $isParam): bool ``` Procedural style ``` xmlwriter_start_dtd_entity(XMLWriter $writer, string $name, bool $isParam): bool ``` Starts a DTD entity. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `name` The name of the entity. `isParam` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::endDtdEntity()](xmlwriter.enddtdentity) - End current DTD Entity * [XMLWriter::writeDtdEntity()](xmlwriter.writedtdentity) - Write full DTD Entity tag php SolrParams::serialize SolrParams::serialize ===================== (PECL solr >= 0.9.2) SolrParams::serialize — Used for custom serialization ### Description ``` final public SolrParams::serialize(): string ``` Used for custom serialization ### Parameters This function has no parameters. ### Return Values Used for custom serialization php SolrQuery::getMltMinWordLength SolrQuery::getMltMinWordLength ============================== (PECL solr >= 0.9.2) SolrQuery::getMltMinWordLength — Returns the minimum word length below which words will be ignored ### Description ``` public SolrQuery::getMltMinWordLength(): int ``` Returns the minimum word length below which words will be ignored ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php Imagick::pingImageBlob Imagick::pingImageBlob ====================== (PECL imagick 2, PECL imagick 3) Imagick::pingImageBlob — Quickly fetch attributes ### Description ``` public Imagick::pingImageBlob(string $image): bool ``` This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `image` A string containing the image. ### Return Values Returns **`true`** on success. ### Examples **Example #1 Using **Imagick::pingImageBlob()**** Pinging an image from a string ``` <?php /* read image contents */ $image = file_get_contents("test.jpg"); /* create new imagick object */ $im = new Imagick(); /* pass the string to the imagick object */ $im->pingImageBlob($image); /* output image width and height */ echo $im->getImageWidth() . 'x' . $im->getImageHeight(); ?> ``` ### See Also * [Imagick::pingImage()](imagick.pingimage) - Fetch basic attributes about the image * [Imagick::pingImageFile()](imagick.pingimagefile) - Get basic image attributes in a lightweight manner * [Imagick::readImage()](imagick.readimage) - Reads image from filename * [Imagick::readImageBlob()](imagick.readimageblob) - Reads image from a binary string * [Imagick::readImageFile()](imagick.readimagefile) - Reads image from open filehandle php output_reset_rewrite_vars output\_reset\_rewrite\_vars ============================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) output\_reset\_rewrite\_vars — Reset URL rewriter values ### Description ``` output_reset_rewrite_vars(): bool ``` This function resets the URL rewriter and removes all rewrite variables previously set by the [output\_add\_rewrite\_var()](function.output-add-rewrite-var) function. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | Before PHP 7.1.0, rewrite vars set by [output\_add\_rewrite\_var()](function.output-add-rewrite-var) use the same Session module trans sid output buffer. Since PHP 7.1.0, dedicated output buffer is used and **output\_reset\_rewrite\_vars()** only removes rewrite vars defined by [output\_add\_rewrite\_var()](function.output-add-rewrite-var). | ### Examples **Example #1 **output\_reset\_rewrite\_vars()** example** ``` <?php session_start(); output_add_rewrite_var('var', 'value'); echo '<a href="file.php">link</a>'; ob_flush(); output_reset_rewrite_vars(); echo '<a href="file.php">link</a>'; ?> ``` The above example will output: ``` <a href="file.php?PHPSESSID=xxx&var=value">link</a> <a href="file.php">link</a> ``` ### See Also * [output\_add\_rewrite\_var()](function.output-add-rewrite-var) - Add URL rewriter values * [ob\_flush()](function.ob-flush) - Flush (send) the output buffer * [ob\_list\_handlers()](function.ob-list-handlers) - List all output handlers in use * [url\_rewriter.tags](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.tags) * [url\_rewriter.hosts](https://www.php.net/manual/en/outcontrol.configuration.php#ini.url-rewriter.hosts) * [session.trans\_sid\_tags](https://www.php.net/manual/en/session.configuration.php#ini.session.trans-sid-tags) * [session.trans\_sid\_hosts](https://www.php.net/manual/en/session.configuration.php#ini.session.trans-sid-hosts) php curl_errno curl\_errno =========== (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) curl\_errno — Return the last error number ### Description ``` curl_errno(CurlHandle $handle): int ``` Returns the error number for the last cURL operation. ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). ### Return Values Returns the error number or `0` (zero) if no error occurred. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | ### Examples **Example #1 **curl\_errno()** example** ``` <?php // Create a curl handle to a non-existing location $ch = curl_init('http://404.php.net/'); // Execute curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); // Check if any error occurred if(curl_errno($ch)) {     echo 'Curl error: ' . curl_error($ch); } // Close handle curl_close($ch); ?> ``` ### See Also * [curl\_error()](function.curl-error) - Return a string containing the last error for the current session * [» Curl error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) php stripcslashes stripcslashes ============= (PHP 4, PHP 5, PHP 7, PHP 8) stripcslashes — Un-quote string quoted with [addcslashes()](function.addcslashes) ### Description ``` stripcslashes(string $string): string ``` Returns a string with backslashes stripped off. Recognizes C-like `\n`, `\r` ..., octal and hexadecimal representation. ### Parameters `string` The string to be unescaped. ### Return Values Returns the unescaped string. ### Examples **Example #1 **stripcslashes()** example** ``` <?php var_dump(stripcslashes('I\'d have a coffee.\nNot a problem.') === "I'd have a coffee. Not a problem."); // true ?> ``` ### See Also * [addcslashes()](function.addcslashes) - Quote string with slashes in a C style php ImagickDraw::getTextAlignment ImagickDraw::getTextAlignment ============================= (PECL imagick 2, PECL imagick 3) ImagickDraw::getTextAlignment — Returns the text alignment ### Description ``` public ImagickDraw::getTextAlignment(): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the alignment applied when annotating with text. ### Return Values Returns a [ALIGN](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.align) constant (`imagick::ALIGN_*`), and 0 if no align is set. php readfile readfile ======== (PHP 4, PHP 5, PHP 7, PHP 8) readfile — Outputs a file ### Description ``` readfile(string $filename, bool $use_include_path = false, ?resource $context = null): int|false ``` Reads a file and writes it to the output buffer. ### Parameters `filename` The filename being read. `use_include_path` You can use the optional second parameter and set it to **`true`**, if you want to search for the file in the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path), too. `context` A [context stream](https://www.php.net/manual/en/stream.contexts.php) resource. ### Return Values Returns the number of bytes read from the file on success, or **`false`** on failure ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 Forcing a download using **readfile()**** ``` <?php $file = 'monkey.gif'; if (file_exists($file)) {     header('Content-Description: File Transfer');     header('Content-Type: application/octet-stream');     header('Content-Disposition: attachment; filename="'.basename($file).'"');     header('Expires: 0');     header('Cache-Control: must-revalidate');     header('Pragma: public');     header('Content-Length: ' . filesize($file));     readfile($file);     exit; } ?> ``` The above example will output something similar to: ### Notes > > **Note**: > > > **readfile()** will not present any memory issues, even when sending large files, on its own. If you encounter an out of memory error ensure that output buffering is off with [ob\_get\_level()](function.ob-get-level). > > **Tip**A URL can be used as a filename with this function if the [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) have been enabled. See [fopen()](function.fopen) for more details on how to specify the filename. See the [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide. ### See Also * [fpassthru()](function.fpassthru) - Output all remaining data on a file pointer * [file()](function.file) - Reads entire file into an array * [fopen()](function.fopen) - Opens file or URL * [include](function.include) - include * [require](function.require) - require * [virtual()](function.virtual) - Perform an Apache sub-request * [file\_get\_contents()](function.file-get-contents) - Reads entire file into a string * [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) php ZipArchive::close ZipArchive::close ================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::close — Close the active archive (opened or newly created) ### Description ``` public ZipArchive::close(): bool ``` Close opened or created archive and save changes. This method is automatically called at the end of the script. If the archive contains no files, the file is completely removed (no empty archive is written). ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php date_format date\_format ============ (PHP 5 >= 5.2.0, PHP 7, PHP 8) date\_format — Alias of [DateTime::format()](datetime.format) ### Description This function is an alias of: [DateTime::format()](datetime.format) php Yaf_Session::offsetSet Yaf\_Session::offsetSet ======================= (Yaf >=1.0.0) Yaf\_Session::offsetSet — The offsetSet purpose ### Description ``` public Yaf_Session::offsetSet(string $name, string $value): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `value` ### Return Values php The NoRewindIterator class The NoRewindIterator class ========================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) This iterator ignores rewind operations. This allows processing an iterator in multiple partial foreach loops. Class synopsis -------------- class **NoRewindIterator** extends [IteratorIterator](class.iteratoriterator) { /\* Methods \*/ public [\_\_construct](norewinditerator.construct)([Iterator](class.iterator) `$iterator`) ``` public current(): mixed ``` ``` public getInnerIterator(): iterator ``` ``` public key(): mixed ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public valid(): bool ``` /\* Inherited methods \*/ ``` public IteratorIterator::current(): mixed ``` ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` ``` public IteratorIterator::key(): mixed ``` ``` public IteratorIterator::next(): void ``` ``` public IteratorIterator::rewind(): void ``` ``` public IteratorIterator::valid(): bool ``` } Table of Contents ----------------- * [NoRewindIterator::\_\_construct](norewinditerator.construct) — Construct a NoRewindIterator * [NoRewindIterator::current](norewinditerator.current) — Get the current value * [NoRewindIterator::getInnerIterator](norewinditerator.getinneriterator) — Get the inner iterator * [NoRewindIterator::key](norewinditerator.key) — Get the current key * [NoRewindIterator::next](norewinditerator.next) — Forward to the next element * [NoRewindIterator::rewind](norewinditerator.rewind) — Prevents the rewind operation on the inner iterator * [NoRewindIterator::valid](norewinditerator.valid) — Validates the iterator
programming_docs
php Gmagick::setimagedepth Gmagick::setimagedepth ====================== (PECL gmagick >= Unknown) Gmagick::setimagedepth — Sets the image depth ### Description ``` public Gmagick::setimagedepth(int $depth): Gmagick ``` Sets the image depth. ### Parameters `depth` The image depth in bits: 8, 16, or 32. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Gmagick::setimagedispose Gmagick::setimagedispose ======================== (PECL gmagick >= Unknown) Gmagick::setimagedispose — Sets the image disposal method ### Description ``` public Gmagick::setimagedispose(int $disposeType): Gmagick ``` Sets the image disposal method. ### Parameters `disposeType` The image disposal type. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php GmagickDraw::polygon GmagickDraw::polygon ==================== (PECL gmagick >= Unknown) GmagickDraw::polygon — Draws a polygon ### Description ``` public GmagickDraw::polygon(array $coordinates): GmagickDraw ``` Draws a polygon using the current stroke, stroke width, and fill color or texture, using the specified array of coordinates. ### Parameters `coordinates` coordinate array ### Return Values The [GmagickDraw](class.gmagickdraw) object. php SolrQuery::setTermsIncludeLowerBound SolrQuery::setTermsIncludeLowerBound ==================================== (PECL solr >= 0.9.2) SolrQuery::setTermsIncludeLowerBound — Include the lower bound term in the result set ### Description ``` public SolrQuery::setTermsIncludeLowerBound(bool $flag): SolrQuery ``` Include the lower bound term in the result set. ### Parameters `flag` Include the lower bound term in the result set ### Return Values Returns the current SolrQuery object, if the return value is used. php XMLWriter::fullEndElement XMLWriter::fullEndElement ========================= xmlwriter\_full\_end\_element ============================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL xmlwriter >= 2.0.4) XMLWriter::fullEndElement -- xmlwriter\_full\_end\_element — End current element ### Description Object-oriented style ``` public XMLWriter::fullEndElement(): bool ``` Procedural style ``` xmlwriter_full_end_element(XMLWriter $writer): bool ``` End the current xml element. Writes an end tag even if the element is empty. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::endElement()](xmlwriter.endelement) - End current element php GearmanClient::addTask GearmanClient::addTask ====================== (PECL gearman >= 0.5.0) GearmanClient::addTask — Add a task to be run in parallel ### Description ``` public GearmanClient::addTask( string $function_name, string $workload, mixed &$context = ?, string $unique = ? ): GearmanTask ``` Adds a task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call [GearmanClient::runTasks()](gearmanclient.runtasks) to perform the work. Note that enough workers need to be available for the tasks to all run in parallel. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `context` Application context to associate with a task `unique` A unique ID used to identify a particular task ### Return Values A [GearmanTask](class.gearmantask) object or **`false`** if the task could not be added. ### Examples **Example #1 Basic submission of two tasks** ``` <?php # Create our gearman client $gmclient= new GearmanClient();  # add the default job server $gmclient->addServer();  # set a function to be called when the work is complete $gmclient->setCompleteCallback("complete");  # add a task to perform the "reverse" function on the string "Hello World!" $gmclient->addTask("reverse", "Hello World!", null, "1");  # add another task to perform the "reverse" function on the string "!dlroW olleH" $gmclient->addTask("reverse", "!dlroW olleH", null, "2");  # run the tasks $gmclient->runTasks();  function complete($task)  {    print "COMPLETE: " . $task->unique() . ", " . $task->data() . "\n";  } ?> ``` The above example will output something similar to: ``` COMPLETE: 2, Hello World! COMPLETE: 1, !dlroW olleH ``` **Example #2 Basic submission of two tasks with passing application context** ``` <?php $client = new GearmanClient(); $client->addServer(); # set a function to be called when the work is complete $client->setCompleteCallback("reverse_complete"); # Add some tasks for a placeholder of where to put the results $results = array(); $client->addTask("reverse", "Hello World!", $results, "t1"); $client->addTask("reverse", "!dlroW olleH", $results, "t2"); $client->runTasks(); # The results should now be filled in from the callbacks foreach ($results as $id => $result)    echo $id . ": " . $result['handle'] . ", " . $result['data'] . "\n"; function reverse_complete($task, $results) {    $results[$task->unique()] = array("handle"=>$task->jobHandle(), "data"=>$task->data()); } ?> ``` The above example will output something similar to: ``` t2: H.foo:21, Hello World! t1: H:foo:22, !dlroW olleH ``` ### See Also * [GearmanClient::addTaskHigh()](gearmanclient.addtaskhigh) - Add a high priority task to run in parallel * [GearmanClient::addTaskLow()](gearmanclient.addtasklow) - Add a low priority task to run in parallel * [GearmanClient::addTaskBackground()](gearmanclient.addtaskbackground) - Add a background task to be run in parallel * [GearmanClient::addTaskHighBackground()](gearmanclient.addtaskhighbackground) - Add a high priority background task to be run in parallel * [GearmanClient::addTaskLowBackground()](gearmanclient.addtasklowbackground) - Add a low priority background task to be run in parallel * [GearmanClient::runTasks()](gearmanclient.runtasks) - Run a list of tasks in parallel php SVM::__construct SVM::\_\_construct ================== (PECL svm >= 0.1.0) SVM::\_\_construct — Construct a new SVM object ### Description public **SVM::\_\_construct**() Constructs a new SVM object ready to accept training data. ### Parameters This function has no parameters. ### Errors/Exceptions Throws a **SVMException** if the libsvm library could not be loaded. php SolrDisMaxQuery::useDisMaxQueryParser SolrDisMaxQuery::useDisMaxQueryParser ===================================== (No version information available, might only be in Git) SolrDisMaxQuery::useDisMaxQueryParser — Switch QueryParser to be DisMax Query Parser ### Description ``` public SolrDisMaxQuery::useDisMaxQueryParser(): SolrDisMaxQuery ``` Switch QueryParser to be DisMax Query Parser ### Parameters This function has no parameters. ### Return Values [SolrDisMaxQuery](class.solrdismaxquery) ### Examples **Example #1 **SolrDisMaxQuery::useDisMaxQueryParser()** example** ``` <?php $dismaxQuery = new SolrDisMaxQuery(); $dismaxQuery->useDisMaxQueryParser(); echo $dismaxQuery; ?> ``` The above example will output something similar to: ``` defType=dismax ``` ### See Also * **SolrDisMaxQuery::useDisMaxQueryParser()** php gnupg_keyinfo gnupg\_keyinfo ============== (PECL gnupg >= 0.1) gnupg\_keyinfo — Returns an array with information about all keys that matches the given pattern ### Description ``` gnupg_keyinfo(resource $identifier, string $pattern): array ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. `pattern` The pattern being checked against the keys. ### Return Values Returns an array with information about all keys that matches the given pattern or **`false`**, if an error has occurred. ### Examples **Example #1 Procedural **gnupg\_keyinfo()** example** ``` <?php $res = gnupg_init(); $info = gnupg_keyinfo($res, 'test'); print_r($info); ?> ``` **Example #2 OO **gnupg\_keyinfo()** example** ``` <?php $gpg = new gnupg(); $info = $gpg->keyinfo("test"); print_r($info); ?> ``` php mb_strrpos mb\_strrpos =========== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_strrpos — Find position of last occurrence of a string in a string ### Description ``` mb_strrpos( string $haystack, string $needle, int $offset = 0, ?string $encoding = null ): int|false ``` Performs a multibyte safe [strrpos()](function.strrpos) operation based on the number of characters. `needle` position is counted from the beginning of `haystack`. First character's position is 0. Second character position is 1. ### Parameters `haystack` The string being checked, for the last occurrence of `needle` `needle` The string to find in `haystack`. `offset` May be specified to begin searching an arbitrary number of characters into the string. Negative values will stop searching at an arbitrary point prior to the end of the string. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values Returns the numeric position of the last occurrence of `needle` in the `haystack` string. If `needle` is not found, it returns **`false`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `needle` now accepts an empty string. | | 8.0.0 | Passing the `encoding` as the third argument instead of an offset has been removed. | | 8.0.0 | `encoding` is nullable now. | ### See Also * [mb\_strpos()](function.mb-strpos) - Find position of first occurrence of string in a string * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding * [strrpos()](function.strrpos) - Find the position of the last occurrence of a substring in a string php Componere\Abstract\Definition::addInterface Componere\Abstract\Definition::addInterface =========================================== (Componere 2 >= 2.1.0) Componere\Abstract\Definition::addInterface — Add Interface ### Description ``` public Componere\Abstract\Definition::addInterface(string $interface): Definition ``` Shall implement the given interface on the current definition ### Parameters `interface` The case insensitive name of an interface ### Return Values The current Definition ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if Definition was registered php openssl_get_curve_names openssl\_get\_curve\_names ========================== (PHP 7 >= 7.1.0, PHP 8) openssl\_get\_curve\_names — Gets list of available curve names for ECC ### Description ``` openssl_get_curve_names(): array|false ``` Gets the list of available curve names for use in Elliptic curve cryptography (ECC) for public/private key operations. The two most widely standardized/supported curves are *prime256v1* (NIST P-256) and *secp384r1* (NIST P-384). **Approximate Equivalancies of AES, RSA, DSA and ECC Keysizes**| AES Symmetric Keysize (Bits) | RSA and DSA Keysize (Bits) | ECC Keysize (Bits) | | --- | --- | --- | | 80 | 1024 | 160 | | 112 | 2048 | 224 | | 128 | 3072 | 256 | | 192 | 7680 | 384 | | 256 | 15360 | 512 | [» NIST recommends using ECC curves with at least 256 bits](http://dx.doi.org/10.6028/NIST.SP.800-57pt1r4). ### Parameters This function has no parameters. ### Return Values An array of available curve names, or **`false`** on failure. ### Examples **Example #1 **openssl\_get\_curve\_names()** example** ``` <?php $curve_names = openssl_get_curve_names(); print_r($curve_names); ?> ``` The above example will output something similar to: ``` Array ( [0] => secp112r1 [1] => secp112r2 [2] => secp128r1 [3] => secp128r2 [4] => secp160k1 [5] => secp160r1 [6] => secp160r2 [7] => secp192k1 [8] => secp224k1 [9] => secp224r1 [10] => secp256k1 [11] => secp384r1 [12] => secp521r1 [13] => prime192v1 [14] => prime192v2 [15] => prime192v3 [16] => prime239v1 [17] => prime239v2 [18] => prime239v3 [19] => prime256v1 [20] => sect113r1 [21] => sect113r2 [22] => sect131r1 [23] => sect131r2 [24] => sect163k1 [25] => sect163r1 [26] => sect163r2 [27] => sect193r1 [28] => sect193r2 [29] => sect233k1 [30] => sect233r1 [31] => sect239k1 [32] => sect283k1 [33] => sect283r1 [34] => sect409k1 [35] => sect409r1 [36] => sect571k1 [37] => sect571r1 [38] => c2pnb163v1 [39] => c2pnb163v2 [40] => c2pnb163v3 [41] => c2pnb176v1 [42] => c2tnb191v1 [43] => c2tnb191v2 [44] => c2tnb191v3 [45] => c2pnb208w1 [46] => c2tnb239v1 [47] => c2tnb239v2 [48] => c2tnb239v3 [49] => c2pnb272w1 [50] => c2pnb304w1 [51] => c2tnb359v1 [52] => c2pnb368w1 [53] => c2tnb431r1 [54] => wap-wsg-idm-ecid-wtls1 [55] => wap-wsg-idm-ecid-wtls3 [56] => wap-wsg-idm-ecid-wtls4 [57] => wap-wsg-idm-ecid-wtls5 [58] => wap-wsg-idm-ecid-wtls6 [59] => wap-wsg-idm-ecid-wtls7 [60] => wap-wsg-idm-ecid-wtls8 [61] => wap-wsg-idm-ecid-wtls9 [62] => wap-wsg-idm-ecid-wtls10 [63] => wap-wsg-idm-ecid-wtls11 [64] => wap-wsg-idm-ecid-wtls12 [65] => Oakley-EC2N-3 [66] => Oakley-EC2N-4 [67] => brainpoolP160r1 [68] => brainpoolP160t1 [69] => brainpoolP192r1 [70] => brainpoolP192t1 [71] => brainpoolP224r1 [72] => brainpoolP224t1 [73] => brainpoolP256r1 [74] => brainpoolP256t1 [75] => brainpoolP320r1 [76] => brainpoolP320t1 [77] => brainpoolP384r1 [78] => brainpoolP384t1 [79] => brainpoolP512r1 [80] => brainpoolP512t1 ) ``` php nl2br nl2br ===== (PHP 4, PHP 5, PHP 7, PHP 8) nl2br — Inserts HTML line breaks before all newlines in a string ### Description ``` nl2br(string $string, bool $use_xhtml = true): string ``` Returns `string` with `<br />` or `<br>` inserted before all newlines (`\r\n`, `\n\r`, `\n` and `\r`). ### Parameters `string` The input string. `use_xhtml` Whether to use XHTML compatible line breaks or not. ### Return Values Returns the altered string. ### Examples **Example #1 Using **nl2br()**** ``` <?php echo nl2br("foo isn't\n bar"); ?> ``` The above example will output: ``` foo isn't<br /> bar ``` **Example #2 Generating valid HTML markup using the `use_xhtml` parameter** ``` <?php echo nl2br("Welcome\r\nThis is my HTML document", false); ?> ``` The above example will output: ``` Welcome<br> This is my HTML document ``` **Example #3 Various newline separators** ``` <?php $string = "This\r\nis\n\ra\nstring\r"; echo nl2br($string); ?> ``` The above example will output: ``` This<br /> is<br /> a<br /> string<br /> ``` ### See Also * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities * [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities * [wordwrap()](function.wordwrap) - Wraps a string to a given number of characters * [str\_replace()](function.str-replace) - Replace all occurrences of the search string with the replacement string php eio_fstatvfs eio\_fstatvfs ============= (PECL eio >= 0.0.1dev) eio\_fstatvfs — Get file system statistics ### Description ``` eio_fstatvfs( mixed $fd, int $pri, callable $callback, mixed $data = ? ): resource ``` **eio\_fstatvfs()** returns file system statistics in `result` of `callback`. ### Parameters `fd` A file descriptor of a file within the mounted file system. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_fstatvfs()** returns request resource on success, or **`false`** on failure. ### See Also * [eio\_statvfs()](function.eio-statvfs) - Get file system statistics php gethostbynamel gethostbynamel ============== (PHP 4, PHP 5, PHP 7, PHP 8) gethostbynamel — Get a list of IPv4 addresses corresponding to a given Internet host name ### Description ``` gethostbynamel(string $hostname): array|false ``` Returns a list of IPv4 addresses to which the Internet host specified by `hostname` resolves. ### Parameters `hostname` The host name. ### Return Values Returns an array of IPv4 addresses or **`false`** if `hostname` could not be resolved. ### Examples **Example #1 **gethostbynamel()** example** ``` <?php $hosts = gethostbynamel('www.example.com'); print_r($hosts); ?> ``` The above example will output: ``` Array ( [0] => 192.0.34.166 ) ``` ### See Also * [gethostbyname()](function.gethostbyname) - Get the IPv4 address corresponding to a given Internet host name * [gethostbyaddr()](function.gethostbyaddr) - Get the Internet host name corresponding to a given IP address * [checkdnsrr()](function.checkdnsrr) - Check DNS records corresponding to a given Internet host name or IP address * [getmxrr()](function.getmxrr) - Get MX records corresponding to a given Internet host name * the `named(8)` manual page php gethostname gethostname =========== (PHP 5 >= 5.3.0, PHP 7, PHP 8) gethostname — Gets the host name ### Description ``` gethostname(): string|false ``` **gethostname()** gets the standard host name for the local machine. ### Parameters This function has no parameters. ### Return Values Returns a string with the hostname on success, otherwise **`false`** is returned. ### Examples **Example #1 A simple **gethostname()** example** ``` <?php echo gethostname(); // may output e.g,: sandie ?> ``` ### See Also * [gethostbyname()](function.gethostbyname) - Get the IPv4 address corresponding to a given Internet host name * [gethostbyaddr()](function.gethostbyaddr) - Get the Internet host name corresponding to a given IP address * [php\_uname()](function.php-uname) - Returns information about the operating system PHP is running on php SolrUtils::digestXmlResponse SolrUtils::digestXmlResponse ============================ (PECL solr >= 0.9.2) SolrUtils::digestXmlResponse — Parses an response XML string into a SolrObject ### Description ``` public static SolrUtils::digestXmlResponse(string $xmlresponse, int $parse_mode = 0): SolrObject ``` This method parses an response XML string from the Apache Solr server into a SolrObject. It throws a SolrException if there was an error. ### Parameters `xmlresponse` The XML response string from the Solr server. `parse_mode` Use SolrResponse::PARSE\_SOLR\_OBJ or SolrResponse::PARSE\_SOLR\_DOC ### Return Values Returns the SolrObject representing the XML response. If the parse\_mode parameter is set to SolrResponse::PARSE\_SOLR\_OBJ Solr documents will be parses as SolrObject instances. If it is set to SolrResponse::PARSE\_SOLR\_DOC, they will be parsed as SolrDocument instances.
programming_docs
php Yar_Client::__call Yar\_Client::\_\_call ===================== (PECL yar >= 1.0.0) Yar\_Client::\_\_call — Call service ### Description ``` public Yar_Client::__call(string $method, array $parameters): void ``` Issue a call to remote RPC method. ### Parameters `method` Remote RPC method name. `parameters` Parameters. ### Return Values ### Examples **Example #1 **Yar\_Client::\_\_call()** example** ``` <?php $client = new Yar_Client("http://host/api/"); /* call remote service */ $result = $client->some_method("parameter"); ?> ``` The above example will output something similar to: ### See Also * [Yar\_Client::setOpt()](yar-client.setopt) - Set calling contexts php ob_get_clean ob\_get\_clean ============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) ob\_get\_clean — Get current buffer contents and delete current output buffer ### Description ``` ob_get_clean(): string|false ``` Gets the current buffer contents and delete current output buffer. **ob\_get\_clean()** essentially executes both [ob\_get\_contents()](function.ob-get-contents) and [ob\_end\_clean()](function.ob-end-clean). The output buffer must be started by [ob\_start()](function.ob-start) with [PHP\_OUTPUT\_HANDLER\_CLEANABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-cleanable) and [PHP\_OUTPUT\_HANDLER\_REMOVABLE](https://www.php.net/manual/en/outcontrol.constants.php#constant.php-output-handler-removable) flags. Otherwise **ob\_get\_clean()** will not work. ### Parameters This function has no parameters. ### Return Values Returns the contents of the output buffer and end output buffering. If output buffering isn't active then **`false`** is returned. ### Examples **Example #1 A simple **ob\_get\_clean()** example** ``` <?php ob_start(); echo "Hello World"; $out = ob_get_clean(); $out = strtolower($out); var_dump($out); ?> ``` The above example will output: ``` string(11) "hello world" ``` ### See Also * [ob\_get\_contents()](function.ob-get-contents) - Return the contents of the output buffer * [ob\_start()](function.ob-start) - Turn on output buffering php runkit7_method_rename runkit7\_method\_rename ======================= (PECL runkit7 >= Unknown) runkit7\_method\_rename — Dynamically changes the name of the given method ### Description ``` runkit7_method_rename(string $class_name, string $source_method_name, string $target_method_name): bool ``` > **Note**: This function cannot be used to manipulate the currently running (or chained) method. > > ### Parameters `class_name` The class in which to rename the method `source_method_name` The name of the method to rename `target_method_name` The new name to give to the renamed method ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **runkit7\_method\_rename()** example** ``` <?php class Example {     function foo() {         return "foo!\n";     } } // Rename the 'foo' method to 'bar' runkit7_method_rename(     'Example',     'foo',     'bar' ); // output renamed function echo (new Example)->bar(); ?> ``` The above example will output: ``` foo! ``` ### See Also * [runkit7\_method\_add()](function.runkit7-method-add) - Dynamically adds a new method to a given class * [runkit7\_method\_copy()](function.runkit7-method-copy) - Copies a method from class to another * [runkit7\_method\_redefine()](function.runkit7-method-redefine) - Dynamically changes the code of the given method * [runkit7\_method\_remove()](function.runkit7-method-remove) - Dynamically removes the given method * [runkit7\_function\_rename()](function.runkit7-function-rename) - Change a function's name php imagesettile imagesettile ============ (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagesettile — Set the tile image for filling ### Description ``` imagesettile(GdImage $image, GdImage $tile): bool ``` **imagesettile()** sets the tile image to be used by all region filling functions (such as [imagefill()](function.imagefill) and [imagefilledpolygon()](function.imagefilledpolygon)) when filling with the special color **`IMG_COLOR_TILED`**. A tile is an image used to fill an area with a repeated pattern. *Any* GD image can be used as a tile, and by setting the transparent color index of the tile image with [imagecolortransparent()](function.imagecolortransparent), a tile allows certain parts of the underlying area to shine through can be created. **Caution** You need not take special action when you are finished with a tile, but if you destroy the tile image (or let PHP destroy it), you must not use the **`IMG_COLOR_TILED`** color until you have set a new tile image! ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `tile` The image object to be used as a tile. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` and `tile` expect [GdImage](class.gdimage) instances now; previously, resources were expected. | ### Examples **Example #1 **imagesettile()** example** ``` <?php // Load an external image $zend = imagecreatefromgif('./zend.gif'); // Create a 200x200 image $im = imagecreatetruecolor(200, 200); // Set the tile imagesettile($im, $zend); // Make the image repeat imagefilledrectangle($im, 0, 0, 199, 199, IMG_COLOR_TILED); // Output image to the browser header('Content-Type: image/png'); imagepng($im); imagedestroy($im); imagedestroy($zend); ?> ``` The above example will output something similar to: php fgetc fgetc ===== (PHP 4, PHP 5, PHP 7, PHP 8) fgetc — Gets character from file pointer ### Description ``` fgetc(resource $stream): string|false ``` Gets a character from the given file pointer. ### Parameters `stream` The file pointer must be valid, and must point to a file successfully opened by [fopen()](function.fopen) or [fsockopen()](function.fsockopen) (and not yet closed by [fclose()](function.fclose)). ### Return Values Returns a string containing a single character read from the file pointed to by `stream`. Returns **`false`** on EOF. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Examples **Example #1 A **fgetc()** example** ``` <?php $fp = fopen('somefile.txt', 'r'); if (!$fp) {     echo 'Could not open file somefile.txt'; } while (false !== ($char = fgetc($fp))) {     echo "$char\n"; } ?> ``` ### Notes > **Note**: This function is binary-safe. > > ### See Also * [fread()](function.fread) - Binary-safe file read * [fopen()](function.fopen) - Opens file or URL * [popen()](function.popen) - Opens process file pointer * [fsockopen()](function.fsockopen) - Open Internet or Unix domain socket connection * [fgets()](function.fgets) - Gets line from file pointer php Imagick::render Imagick::render =============== (PECL imagick 2, PECL imagick 3) Imagick::render — Renders all preceding drawing commands ### Description ``` public Imagick::render(): bool ``` Renders all preceding drawing commands. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. php timezone_name_get timezone\_name\_get =================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) timezone\_name\_get — Alias of [DateTimeZone::getName()](datetimezone.getname) ### Description This function is an alias of: [DateTimeZone::getName()](datetimezone.getname) php sodium_crypto_aead_chacha20poly1305_ietf_keygen sodium\_crypto\_aead\_chacha20poly1305\_ietf\_keygen ==================================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_aead\_chacha20poly1305\_ietf\_keygen — Generate a random ChaCha20-Poly1305 (IETF) key. ### Description ``` sodium_crypto_aead_chacha20poly1305_ietf_keygen(): string ``` Generate a random key for use with [sodium\_crypto\_aead\_chacha20poly1305\_ietf\_encrypt()](function.sodium-crypto-aead-chacha20poly1305-ietf-encrypt) and [sodium\_crypto\_aead\_chacha20poly1305\_ietf\_decrypt()](function.sodium-crypto-aead-chacha20poly1305-ietf-decrypt). ### Parameters This function has no parameters. ### Return Values Returns a 256-bit random key. php ReflectionMethod::isDestructor ReflectionMethod::isDestructor ============================== (PHP 5, PHP 7, PHP 8) ReflectionMethod::isDestructor — Checks if method is a destructor ### Description ``` public ReflectionMethod::isDestructor(): bool ``` Checks if the method is a destructor. ### Parameters This function has no parameters. ### Return Values **`true`** if the method is a destructor, otherwise **`false`** ### See Also * [ReflectionMethod::isConstructor()](reflectionmethod.isconstructor) - Checks if method is a constructor php pclose pclose ====== (PHP 4, PHP 5, PHP 7, PHP 8) pclose — Closes process file pointer ### Description ``` pclose(resource $handle): int ``` Closes a file pointer to a pipe opened by [popen()](function.popen). ### Parameters `handle` The file pointer must be valid, and must have been returned by a successful call to [popen()](function.popen). ### Return Values Returns the termination status of the process that was run. In case of an error then `-1` is returned. > > **Note**: > > > If PHP has been compiled with --enable-sigchild, the return value of this function is undefined. > > ### Examples **Example #1 **pclose()** example** ``` <?php $handle = popen('/bin/ls', 'r'); pclose($handle); ?> ``` ### Notes > > **Note**: **Unix Only:** > > > > **pclose()** is internally implemented using the `waitpid(3)` system call. To obtain the real exit status code the [pcntl\_wexitstatus()](function.pcntl-wexitstatus) function should be used. > > ### See Also * [popen()](function.popen) - Opens process file pointer php SolrClient::query SolrClient::query ================= (PECL solr >= 0.9.2) SolrClient::query — Sends a query to the server ### Description ``` public SolrClient::query(SolrParams $query): SolrQueryResponse ``` Sends a query to the server. ### Parameters `query` A [SolrParams](class.solrparams) object. It is recommended to use [SolrQuery](class.solrquery) for advanced queries. ### Return Values Returns a [SolrQueryResponse](class.solrqueryresponse) object on success and throws an exception on failure. ### Errors/Exceptions Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to satisfy the query. ### Examples **Example #1 **SolrClient::query()** example** ``` <?php $options = array (     'hostname' => 'localhost',     'login'    => 'username',     'password' => 'password',     'port'     => '8983', ); $client = new SolrClient($options); $query = new SolrQuery(); $query->setQuery('lucene'); $query->setStart(0); $query->setRows(50); $query->addField('cat')->addField('features')->addField('id')->addField('timestamp'); $query_response = $client->query($query); $response = $query_response->getResponse(); print_r($response); ?> ``` The above example will output something similar to: ``` SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 3 [params] => SolrObject Object ( [fl] => cat,features,id,timestamp [indent] => on [start] => 0 [q] => lucene [wt] => xml [version] => 2.2 [rows] => 50 ) ) [response] => SolrObject Object ( [numFound] => 1 [start] => 0 [docs] => Array ( [0] => SolrObject Object ( [id] => SOLR1000 [cat] => Array ( [0] => software [1] => search ) [features] => Array ( [0] => Advanced Full-Text Search Capabilities using Lucene [1] => Optimized for High Volume Web Traffic [2] => Standards Based Open Interfaces - XML and HTTP [3] => Comprehensive HTML Administration Interfaces [4] => Scalability - Efficient Replication to other Solr Search Servers [5] => Flexible and Adaptable with XML configuration and Schema [6] => Good unicode support: héllo (hello with an accent over the e) ) ) ) ) ) ``` php ReflectionObject::export ReflectionObject::export ======================== (PHP 5, PHP 7) ReflectionObject::export — Export **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionObject::export(string $argument, bool $return = ?): string ``` Exports a reflection. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `argument` The reflection to export. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values If the `return` parameter is set to **`true`**, then the export is returned as a string, otherwise **`null`** is returned. ### See Also * [ReflectionObject::\_\_construct()](reflectionobject.construct) - Constructs a ReflectionObject php fdf_set_javascript_action fdf\_set\_javascript\_action ============================ (PHP 4 >= 4.0.2, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_set\_javascript\_action — Sets an javascript action of a field ### Description ``` fdf_set_javascript_action( resource $fdf_document, string $fieldname, int $trigger, string $script ): bool ``` Sets a javascript action for the given field. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `fieldname` Name of the FDF field, as a string. `trigger` `script` ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [fdf\_set\_submit\_form\_action()](function.fdf-set-submit-form-action) - Sets a submit form action of a field php ctype_alnum ctype\_alnum ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_alnum — Check for alphanumeric character(s) ### Description ``` ctype_alnum(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are alphanumeric. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in `text` is either a letter or a digit, **`false`** otherwise. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_alnum()** example (using the default locale)** ``` <?php $strings = array('AbCd1zyZ9', 'foo!#$bar'); foreach ($strings as $testcase) {     if (ctype_alnum($testcase)) {         echo "The string $testcase consists of all letters or digits.\n";     } else {         echo "The string $testcase does not consist of all letters or digits.\n";     } } ?> ``` The above example will output: ``` The string AbCd1zyZ9 consists of all letters or digits. The string foo!#$bar does not consist of all letters or digits. ``` ### See Also * [ctype\_alpha()](function.ctype-alpha) - Check for alphabetic character(s) * [ctype\_digit()](function.ctype-digit) - Check for numeric character(s) * [setlocale()](function.setlocale) - Set locale information php Imagick::setImageAlphaChannel Imagick::setImageAlphaChannel ============================= (PECL imagick 2 >= 2.1.0, PECL imagick 3) Imagick::setImageAlphaChannel — Sets image alpha channel ### Description ``` public Imagick::setImageAlphaChannel(int $mode): bool ``` Activate or deactivate image alpha channel. The `mode` is one of the **`Imagick::ALPHACHANNEL_*`** constants. This method is available if Imagick has been compiled against ImageMagick version 6.3.8 or newer. ### Parameters `mode` One of the **`Imagick::ALPHACHANNEL_*`** constants ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### See Also * [Imagick::setImageMatte()](imagick.setimagematte) - Sets the image matte channel * [Imagick Alpha Channel Constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.alphachannel) php The Memcached class The Memcached class =================== Introduction ------------ (PECL memcached >= 0.1.0) Represents a connection to a set of memcached servers. Class synopsis -------------- class **Memcached** { public [\_\_construct](memcached.construct)(?string `$persistent_id` = null) ``` public add(string $key, mixed $value, int $expiration = ?): bool ``` ``` public addByKey( string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` ``` public addServer(string $host, int $port, int $weight = 0): bool ``` ``` public addServers(array $servers): bool ``` ``` public append(string $key, string $value): bool ``` ``` public appendByKey(string $server_key, string $key, string $value): bool ``` ``` public cas( float $cas_token, string $key, mixed $value, int $expiration = ? ): bool ``` ``` public casByKey( float $cas_token, string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` ``` public decrement( string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0 ): int|false ``` ``` public decrementByKey( string $server_key, string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0 ): int|false ``` ``` public delete(string $key, int $time = 0): bool ``` ``` public deleteByKey(string $server_key, string $key, int $time = 0): bool ``` ``` public deleteMulti(array $keys, int $time = 0): array ``` ``` public deleteMultiByKey(string $server_key, array $keys, int $time = 0): bool ``` ``` public fetch(): array ``` ``` public fetchAll(): array|false ``` ``` public flush(int $delay = 0): bool ``` ``` public get(string $key, callable $cache_cb = ?, int $flags = ?): mixed ``` ``` public getAllKeys(): array|false ``` ``` public getByKey( string $server_key, string $key, callable $cache_cb = ?, int $flags = ? ): mixed ``` ``` public getDelayed(array $keys, bool $with_cas = ?, callable $value_cb = ?): bool ``` ``` public getDelayedByKey( string $server_key, array $keys, bool $with_cas = ?, callable $value_cb = ? ): bool ``` ``` public getMulti(array $keys, int $flags = ?): mixed ``` ``` public getMultiByKey(string $server_key, array $keys, int $flags = ?): array|false ``` ``` public getOption(int $option): mixed ``` ``` public getResultCode(): int ``` ``` public getResultMessage(): string ``` ``` public getServerByKey(string $server_key): array ``` ``` public getServerList(): array ``` ``` public getStats(): array|false ``` ``` public getVersion(): array ``` ``` public increment( string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0 ): int|false ``` ``` public incrementByKey( string $server_key, string $key, int $offset = 1, int $initial_value = 0, int $expiry = 0 ): int|false ``` ``` public isPersistent(): bool ``` ``` public isPristine(): bool ``` ``` public prepend(string $key, string $value): bool ``` ``` public prependByKey(string $server_key, string $key, string $value): bool ``` ``` public quit(): bool ``` ``` public replace(string $key, mixed $value, int $expiration = ?): bool ``` ``` public replaceByKey( string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` ``` public resetServerList(): bool ``` ``` public set(string $key, mixed $value, int $expiration = ?): bool ``` ``` public setByKey( string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` ``` public setMulti(array $items, int $expiration = ?): bool ``` ``` public setMultiByKey(string $server_key, array $items, int $expiration = ?): bool ``` ``` public setOption(int $option, mixed $value): bool ``` ``` public setOptions(array $options): bool ``` ``` public setSaslAuthData(string $username, string $password): void ``` ``` public touch(string $key, int $expiration): bool ``` ``` public touchByKey(string $server_key, string $key, int $expiration): bool ``` } Table of Contents ----------------- * [Memcached::add](memcached.add) — Add an item under a new key * [Memcached::addByKey](memcached.addbykey) — Add an item under a new key on a specific server * [Memcached::addServer](memcached.addserver) — Add a server to the server pool * [Memcached::addServers](memcached.addservers) — Add multiple servers to the server pool * [Memcached::append](memcached.append) — Append data to an existing item * [Memcached::appendByKey](memcached.appendbykey) — Append data to an existing item on a specific server * [Memcached::cas](memcached.cas) — Compare and swap an item * [Memcached::casByKey](memcached.casbykey) — Compare and swap an item on a specific server * [Memcached::\_\_construct](memcached.construct) — Create a Memcached instance * [Memcached::decrement](memcached.decrement) — Decrement numeric item's value * [Memcached::decrementByKey](memcached.decrementbykey) — Decrement numeric item's value, stored on a specific server * [Memcached::delete](memcached.delete) — Delete an item * [Memcached::deleteByKey](memcached.deletebykey) — Delete an item from a specific server * [Memcached::deleteMulti](memcached.deletemulti) — Delete multiple items * [Memcached::deleteMultiByKey](memcached.deletemultibykey) — Delete multiple items from a specific server * [Memcached::fetch](memcached.fetch) — Fetch the next result * [Memcached::fetchAll](memcached.fetchall) — Fetch all the remaining results * [Memcached::flush](memcached.flush) — Invalidate all items in the cache * [Memcached::get](memcached.get) — Retrieve an item * [Memcached::getAllKeys](memcached.getallkeys) — Gets the keys stored on all the servers * [Memcached::getByKey](memcached.getbykey) — Retrieve an item from a specific server * [Memcached::getDelayed](memcached.getdelayed) — Request multiple items * [Memcached::getDelayedByKey](memcached.getdelayedbykey) — Request multiple items from a specific server * [Memcached::getMulti](memcached.getmulti) — Retrieve multiple items * [Memcached::getMultiByKey](memcached.getmultibykey) — Retrieve multiple items from a specific server * [Memcached::getOption](memcached.getoption) — Retrieve a Memcached option value * [Memcached::getResultCode](memcached.getresultcode) — Return the result code of the last operation * [Memcached::getResultMessage](memcached.getresultmessage) — Return the message describing the result of the last operation * [Memcached::getServerByKey](memcached.getserverbykey) — Map a key to a server * [Memcached::getServerList](memcached.getserverlist) — Get the list of the servers in the pool * [Memcached::getStats](memcached.getstats) — Get server pool statistics * [Memcached::getVersion](memcached.getversion) — Get server pool version info * [Memcached::increment](memcached.increment) — Increment numeric item's value * [Memcached::incrementByKey](memcached.incrementbykey) — Increment numeric item's value, stored on a specific server * [Memcached::isPersistent](memcached.ispersistent) — Check if a persitent connection to memcache is being used * [Memcached::isPristine](memcached.ispristine) — Check if the instance was recently created * [Memcached::prepend](memcached.prepend) — Prepend data to an existing item * [Memcached::prependByKey](memcached.prependbykey) — Prepend data to an existing item on a specific server * [Memcached::quit](memcached.quit) — Close any open connections * [Memcached::replace](memcached.replace) — Replace the item under an existing key * [Memcached::replaceByKey](memcached.replacebykey) — Replace the item under an existing key on a specific server * [Memcached::resetServerList](memcached.resetserverlist) — Clears all servers from the server list * [Memcached::set](memcached.set) — Store an item * [Memcached::setByKey](memcached.setbykey) — Store an item on a specific server * [Memcached::setMulti](memcached.setmulti) — Store multiple items * [Memcached::setMultiByKey](memcached.setmultibykey) — Store multiple items on a specific server * [Memcached::setOption](memcached.setoption) — Set a Memcached option * [Memcached::setOptions](memcached.setoptions) — Set Memcached options * [Memcached::setSaslAuthData](memcached.setsaslauthdata) — Set the credentials to use for authentication * [Memcached::touch](memcached.touch) — Set a new expiration on an item * [Memcached::touchByKey](memcached.touchbykey) — Set a new expiration on an item on a specific server
programming_docs
php Gmagick::separateimagechannel Gmagick::separateimagechannel ============================= (PECL gmagick >= Unknown) Gmagick::separateimagechannel — Separates a channel from the image ### Description ``` public Gmagick::separateimagechannel(int $channel): Gmagick ``` Separates a channel from the image and returns a grayscale image. A channel is a particular color component of each pixel in the image. ### Parameters `channel` One of the [Channel](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.channel) constant (`Gmagick::CHANNEL_*`). ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php openssl_csr_export_to_file openssl\_csr\_export\_to\_file ============================== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_csr\_export\_to\_file — Exports a CSR to a file ### Description ``` openssl_csr_export_to_file(OpenSSLCertificateSigningRequest|string $csr, string $output_filename, bool $no_text = true): bool ``` **openssl\_csr\_export\_to\_file()** takes the Certificate Signing Request represented by `csr` and saves it in PEM format into the file named by `output_filename`. ### Parameters `csr` See [CSR parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `output_filename` Path to the output file. `no_text` The optional parameter `notext` affects the verbosity of the output; if it is **`false`**, then additional human-readable information is included in the output. The default value of `notext` is **`true`**. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `csr` accepts an [OpenSSLCertificateSigningRequest](class.opensslcertificatesigningrequest) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was accepted. | ### Examples **Example #1 openssl\_csr\_export\_to\_file() example** ``` <?php $subject = array(     "commonName" => "example.com", ); $private_key = openssl_pkey_new(array(     "private_key_bits" => 2048,     "private_key_type" => OPENSSL_KEYTYPE_RSA, )); $csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384') ); openssl_pkey_export_to_file($private_key, 'example-priv.key'); // Along with the subject, the CSR contains the public key corresponding to the private key openssl_csr_export_to_file($csr, 'example-csr.pem'); ?> ``` ### See Also * [openssl\_csr\_export()](function.openssl-csr-export) - Exports a CSR as a string * [openssl\_csr\_new()](function.openssl-csr-new) - Generates a CSR * [openssl\_csr\_sign()](function.openssl-csr-sign) - Sign a CSR with another certificate (or itself) and generate a certificate php wincache_ucache_exists wincache\_ucache\_exists ======================== (PECL wincache >= 1.1.0) wincache\_ucache\_exists — Checks if a variable exists in the user cache ### Description ``` wincache_ucache_exists(string $key): bool ``` Checks if a variable with the `key` exists in the user cache or not. ### Parameters `key` The `key` that was used to store the variable in the cache. `key` is case sensitive. ### Return Values Returns **`true`** if variable with the `key` exitsts, otherwise returns **`false`**. ### Examples **Example #1 Using **wincache\_ucache\_exists()**** ``` <?php if (!wincache_ucache_exists('green'))     wincache_ucache_set('green', 1); var_dump(wincache_ucache_exists('green')); ?> ``` The above example will output: ``` bool(true) ``` ### See Also * [wincache\_ucache\_set()](function.wincache-ucache-set) - Adds a variable in user cache and overwrites a variable if it already exists in the cache * [wincache\_ucache\_add()](function.wincache-ucache-add) - Adds a variable in user cache only if variable does not already exist in the cache * [wincache\_ucache\_get()](function.wincache-ucache-get) - Gets a variable stored in the user cache * [wincache\_ucache\_clear()](function.wincache-ucache-clear) - Deletes entire content of the user cache * [wincache\_ucache\_delete()](function.wincache-ucache-delete) - Deletes variables from the user cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache php The IntlCalendar class The IntlCalendar class ====================== Introduction ------------ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) Class synopsis -------------- class **IntlCalendar** { /\* Constants \*/ public const int [FIELD\_ERA](class.intlcalendar#intlcalendar.constants.field-era); public const int [FIELD\_YEAR](class.intlcalendar#intlcalendar.constants.field-year); public const int [FIELD\_MONTH](class.intlcalendar#intlcalendar.constants.field-month); public const int [FIELD\_WEEK\_OF\_YEAR](class.intlcalendar#intlcalendar.constants.field-week-of-year); public const int [FIELD\_WEEK\_OF\_MONTH](class.intlcalendar#intlcalendar.constants.field-week-of-month); public const int [FIELD\_DATE](class.intlcalendar#intlcalendar.constants.field-date); public const int [FIELD\_DAY\_OF\_YEAR](class.intlcalendar#intlcalendar.constants.field-day-of-year); public const int [FIELD\_DAY\_OF\_WEEK](class.intlcalendar#intlcalendar.constants.field-day-of-week); public const int [FIELD\_DAY\_OF\_WEEK\_IN\_MONTH](class.intlcalendar#intlcalendar.constants.field-day-of-week-in-month); public const int [FIELD\_AM\_PM](class.intlcalendar#intlcalendar.constants.field-am-pm); public const int [FIELD\_HOUR](class.intlcalendar#intlcalendar.constants.field-hour); public const int [FIELD\_HOUR\_OF\_DAY](class.intlcalendar#intlcalendar.constants.field-hour-of-day); public const int [FIELD\_MINUTE](class.intlcalendar#intlcalendar.constants.field-minute); public const int [FIELD\_SECOND](class.intlcalendar#intlcalendar.constants.field-second); public const int [FIELD\_MILLISECOND](class.intlcalendar#intlcalendar.constants.field-millisecond); public const int [FIELD\_ZONE\_OFFSET](class.intlcalendar#intlcalendar.constants.field-zone-offset); public const int [FIELD\_DST\_OFFSET](class.intlcalendar#intlcalendar.constants.field-dst-offset); public const int [FIELD\_YEAR\_WOY](class.intlcalendar#intlcalendar.constants.field-year-woy); public const int [FIELD\_DOW\_LOCAL](class.intlcalendar#intlcalendar.constants.field-dow-local); public const int [FIELD\_EXTENDED\_YEAR](class.intlcalendar#intlcalendar.constants.field-extended-year); public const int [FIELD\_JULIAN\_DAY](class.intlcalendar#intlcalendar.constants.field-julian-day); public const int [FIELD\_MILLISECONDS\_IN\_DAY](class.intlcalendar#intlcalendar.constants.field-milliseconds-in-day); public const int [FIELD\_IS\_LEAP\_MONTH](class.intlcalendar#intlcalendar.constants.field-is-leap-month); public const int [FIELD\_FIELD\_COUNT](class.intlcalendar#intlcalendar.constants.field-field-count); public const int [FIELD\_DAY\_OF\_MONTH](class.intlcalendar#intlcalendar.constants.field-day-of-month); public const int [DOW\_SUNDAY](class.intlcalendar#intlcalendar.constants.dow-sunday); public const int [DOW\_MONDAY](class.intlcalendar#intlcalendar.constants.dow-monday); public const int [DOW\_TUESDAY](class.intlcalendar#intlcalendar.constants.dow-tuesday); public const int [DOW\_WEDNESDAY](class.intlcalendar#intlcalendar.constants.dow-wednesday); public const int [DOW\_THURSDAY](class.intlcalendar#intlcalendar.constants.dow-thursday); public const int [DOW\_FRIDAY](class.intlcalendar#intlcalendar.constants.dow-friday); public const int [DOW\_SATURDAY](class.intlcalendar#intlcalendar.constants.dow-saturday); public const int [DOW\_TYPE\_WEEKDAY](class.intlcalendar#intlcalendar.constants.dow-type-weekday); public const int [DOW\_TYPE\_WEEKEND](class.intlcalendar#intlcalendar.constants.dow-type-weekend); public const int [DOW\_TYPE\_WEEKEND\_OFFSET](class.intlcalendar#intlcalendar.constants.dow-type-weekend-offset); public const int [DOW\_TYPE\_WEEKEND\_CEASE](class.intlcalendar#intlcalendar.constants.dow-type-weekend-cease); public const int [WALLTIME\_FIRST](class.intlcalendar#intlcalendar.constants.walltime-first); public const int [WALLTIME\_LAST](class.intlcalendar#intlcalendar.constants.walltime-last); public const int [WALLTIME\_NEXT\_VALID](class.intlcalendar#intlcalendar.constants.walltime-next-valid); /\* Methods \*/ private [\_\_construct](intlcalendar.construct)() ``` public add(int $field, int $value): bool ``` ``` public after(IntlCalendar $other): bool ``` ``` public before(IntlCalendar $other): bool ``` ``` public clear(?int $field = null): bool ``` ``` public static createInstance(IntlTimeZone|DateTimeZone|string|null $timezone = null, ?string $locale = null): ?IntlCalendar ``` ``` public equals(IntlCalendar $other): bool ``` ``` public fieldDifference(float $timestamp, int $field): int|false ``` ``` public static fromDateTime(DateTime|string $datetime, ?string $locale = null): ?IntlCalendar ``` ``` public get(int $field): int|false ``` ``` public getActualMaximum(int $field): int|false ``` ``` public getActualMinimum(int $field): int|false ``` ``` public static getAvailableLocales(): array ``` ``` public getDayOfWeekType(int $dayOfWeek): int|false ``` ``` public getErrorCode(): int|false ``` ``` public getErrorMessage(): string|false ``` ``` public getFirstDayOfWeek(): int|false ``` ``` public getGreatestMinimum(int $field): int|false ``` ``` public static getKeywordValuesForLocale(string $keyword, string $locale, bool $onlyCommon): IntlIterator|false ``` ``` public getLeastMaximum(int $field): int|false ``` ``` public getLocale(int $type): string|false ``` ``` public getMaximum(int $field): int|false ``` ``` public getMinimalDaysInFirstWeek(): int|false ``` ``` public getMinimum(int $field): int|false ``` ``` public static getNow(): float ``` ``` public getRepeatedWallTimeOption(): int ``` ``` public getSkippedWallTimeOption(): int ``` ``` public getTime(): float|false ``` ``` public getTimeZone(): IntlTimeZone|false ``` ``` public getType(): string ``` ``` public getWeekendTransition(int $dayOfWeek): int|false ``` ``` public inDaylightTime(): bool ``` ``` public isEquivalentTo(IntlCalendar $other): bool ``` ``` public isLenient(): bool ``` ``` public isSet(int $field): bool ``` ``` public isWeekend(?float $timestamp = null): bool ``` ``` public roll(int $field, int|bool $value): bool ``` ``` public set(int $field, int $value): bool ``` ``` public set( int $year, int $month, int $dayOfMonth = NULL, int $hour = NULL, int $minute = NULL, int $second = NULL ): bool ``` ``` public setFirstDayOfWeek(int $dayOfWeek): bool ``` ``` public setLenient(bool $lenient): bool ``` ``` public setMinimalDaysInFirstWeek(int $days): bool ``` ``` public setRepeatedWallTimeOption(int $option): bool ``` ``` public setSkippedWallTimeOption(int $option): bool ``` ``` public setTime(float $timestamp): bool ``` ``` public setTimeZone(IntlTimeZone|DateTimeZone|string|null $timezone): bool ``` ``` public toDateTime(): DateTime|false ``` } Predefined Constants -------------------- **`IntlCalendar::FIELD_ERA`** Calendar field numerically representing an era, for instance `1` for AD and `0` for BC in the Gregorian/Julian calendars and `235` for the Heisei (平成) era in the Japanese calendar. Not all calendars have more than one era. **`IntlCalendar::FIELD_YEAR`** Calendar field for the year. This is not unique across eras. If the calendar type has more than one era, generally the minimum value for this field will be `1`. **`IntlCalendar::FIELD_MONTH`** Calendar field for the month. The month sequence is zero-based, so January (here used to signify the first month of the calendar; this may be called another name, such as Muharram in the Islamic calendar) is represented by `0`, February by `1`, …, December by `11` and, for calendars that have it, the 13th or leap month by `12`. **`IntlCalendar::FIELD_WEEK_OF_YEAR`** Calendar field for the number of the week of the year. This depends on which day of the week is [deemed to start the week](intlcalendar.getfirstdayofweek) and the [minimal number of days in a week](intlcalendar.getminimaldaysinfirstweek). **`IntlCalendar::FIELD_WEEK_OF_MONTH`** Calendar field for the number of the week of the month. This depends on which day of the week is [deemed to start the week](intlcalendar.getfirstdayofweek) and the [minimal number of days in a week](intlcalendar.getminimaldaysinfirstweek). **`IntlCalendar::FIELD_DATE`** Calendar field for the day of the month. The same as **`IntlCalendar::FIELD_DAY_OF_MONTH`**, which has a clearer name. **`IntlCalendar::FIELD_DAY_OF_YEAR`** Calendar field for the day of the year. For the Gregorian calendar, starts with **`1`** and ends with **`365`** or **`366`**. **`IntlCalendar::FIELD_DAY_OF_WEEK`** Calendar field for the day of the week. Its values start with `1` (Sunday, see [**`IntlCalendar::DOW_SUNDAY`**](class.intlcalendar#intlcalendar.constants.dow-sunday) and subsequent constants) and the last valid value is 7 (Saturday). **`IntlCalendar::FIELD_DAY_OF_WEEK_IN_MONTH`** Given a day of the week (Sunday, Monday, …), this calendar field assigns an ordinal to such a day of the week in a specific month. Thus, if the value of this field is `1` and the value of the day of the week is `2` (Monday), then the set day of the month is the 1st Monday of the month; the maximum value is `5`. Additionally, the value `0` and negative values are also allowed. The value `0` encompasses the seven days that occur immediately before the first seven days of a month (which therefore have a ‘day of week in month’ with value `1`). Negative values starts counting from the end of the month – `-1` points to the last occurrence of a day of the week in a month, `-2` to the second last, and so on. Unlike [**`IntlCalendar::FIELD_WEEK_OF_MONTH`**](class.intlcalendar#intlcalendar.constants.field-week-of-month) and [**`IntlCalendar::FIELD_WEEK_OF_YEAR`**](class.intlcalendar#intlcalendar.constants.field-week-of-year), this value does not depend on [IntlCalendar::getFirstDayOfWeek()](intlcalendar.getfirstdayofweek) or on [IntlCalendar::getMinimalDaysInFirstWeek()](intlcalendar.getminimaldaysinfirstweek). The first Monday is the first Monday, even if it occurs in a week that belongs to the previous month. **`IntlCalendar::FIELD_AM_PM`** Calendar field indicating whether a time is before noon (value `0`, AM) or after (`1`). Midnight is AM, noon is PM. **`IntlCalendar::FIELD_HOUR`** Calendar field for the hour, without specifying whether itʼs in the morning or in the afternoon. Valid values are `0` to `11`. **`IntlCalendar::FIELD_HOUR_OF_DAY`** Calendar field for the full (24h) hour of the day. Valid values are `0` to `23`. **`IntlCalendar::FIELD_MINUTE`** Calendar field for the minutes component of the time. **`IntlCalendar::FIELD_SECOND`** Calendar field for the seconds component of the time. **`IntlCalendar::FIELD_MILLISECOND`** Calendar field the milliseconds component of the time. **`IntlCalendar::FIELD_ZONE_OFFSET`** Calendar field indicating the raw offset of the timezone, in milliseconds. The raw offset is the timezone offset, excluding any offset due to daylight saving time. **`IntlCalendar::FIELD_DST_OFFSET`** Calendar field for the daylight saving time offset of the calendarʼs timezone, in milliseconds, if active for calendarʼs time. **`IntlCalendar::FIELD_YEAR_WOY`** Calendar field representing the year for [week of year](class.intlcalendar#intlcalendar.constants.field-week-of-year) purposes. **`IntlCalendar::FIELD_DOW_LOCAL`** Calendar field for the localized day of the week. This is a value between `1` and `7`, `1` being used for the day of the week that matches the value returned by [IntlCalendar::getFirstDayOfWeek()](intlcalendar.getfirstdayofweek). **`IntlCalendar::FIELD_EXTENDED_YEAR`** Calendar field for a year number representation that is continuous across eras. For the Gregorian calendar, the value of this field matches that of **`IntlCalendar::FIELD_YEAR`** for AD years; a BC year `y` is represented by `-y + 1`. **`IntlCalendar::FIELD_JULIAN_DAY`** Calendar field for a modified Julian day number. It is different from a conventional Julian day number in that its transitions occur at local zone midnight rather than at noon UTC. It uniquely identifies a date. **`IntlCalendar::FIELD_MILLISECONDS_IN_DAY`** Calendar field encompassing the information in **`IntlCalendar::FIELD_HOUR_OF_DAY`**, **`IntlCalendar::FIELD_MINUTE`**, **`IntlCalendar::FIELD_SECOND`** and **`IntlCalendar::FIELD_MILLISECOND`**. Range is from the `0` to `24 * 3600 * 1000 - 1`. It is not the amount of milliseconds elapsed in the day since on DST transitions it will have discontinuities analog to those of the wall time. **`IntlCalendar::FIELD_IS_LEAP_MONTH`** Calendar field whose value is `1` for indicating a leap month and `0` otherwise. **`IntlCalendar::FIELD_FIELD_COUNT`** The total number of fields. **`IntlCalendar::FIELD_DAY_OF_MONTH`** Alias for [**`IntlCalendar::FIELD_DATE`**](class.intlcalendar#intlcalendar.constants.field-date). **`IntlCalendar::DOW_SUNDAY`** Sunday. **`IntlCalendar::DOW_MONDAY`** Monday. **`IntlCalendar::DOW_TUESDAY`** Tuesday. **`IntlCalendar::DOW_WEDNESDAY`** Wednesday. **`IntlCalendar::DOW_THURSDAY`** Thursday. **`IntlCalendar::DOW_FRIDAY`** Friday. **`IntlCalendar::DOW_SATURDAY`** Saturday. **`IntlCalendar::DOW_TYPE_WEEKDAY`** Output of [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) indicating a day of week is a weekday. **`IntlCalendar::DOW_TYPE_WEEKEND`** Output of [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) indicating a day of week belongs to the weekend. **`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`** Output of [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) indicating the weekend begins during the given day of week. **`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`** Output of [IntlCalendar::getDayOfWeekType()](intlcalendar.getdayofweektype) indicating the weekend ends during the given day of week. **`IntlCalendar::WALLTIME_FIRST`** Output of [IntlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) indicating that wall times in the skipped range should refer to the same instant as wall times with one hour less and of [IntlCalendar::getRepeatedWallTimeOption()](intlcalendar.getrepeatedwalltimeoption) indicating the wall times in the repeated range should refer to the instant of the first occurrence of such wall time. **`IntlCalendar::WALLTIME_LAST`** Output of [IntlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) indicating that wall times in the skipped range should refer to the same instant as wall times with one hour after and of [IntlCalendar::getRepeatedWallTimeOption()](intlcalendar.getrepeatedwalltimeoption) indicating the wall times in the repeated range should refer to the instant of the second occurrence of such wall time. **`IntlCalendar::WALLTIME_NEXT_VALID`** Output of [IntlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) indicating that wall times in the skipped range should refer to the instant when the daylight saving time transition occurs (begins). Table of Contents ----------------- * [IntlCalendar::add](intlcalendar.add) — Add a (signed) amount of time to a field * [IntlCalendar::after](intlcalendar.after) — Whether this objectʼs time is after that of the passed object * [IntlCalendar::before](intlcalendar.before) — Whether this objectʼs time is before that of the passed object * [IntlCalendar::clear](intlcalendar.clear) — Clear a field or all fields * [IntlCalendar::\_\_construct](intlcalendar.construct) — Private constructor for disallowing instantiation * [IntlCalendar::createInstance](intlcalendar.createinstance) — Create a new IntlCalendar * [IntlCalendar::equals](intlcalendar.equals) — Compare time of two IntlCalendar objects for equality * [IntlCalendar::fieldDifference](intlcalendar.fielddifference) — Calculate difference between given time and this objectʼs time * [IntlCalendar::fromDateTime](intlcalendar.fromdatetime) — Create an IntlCalendar from a DateTime object or string * [IntlCalendar::get](intlcalendar.get) — Get the value for a field * [IntlCalendar::getActualMaximum](intlcalendar.getactualmaximum) — The maximum value for a field, considering the objectʼs current time * [IntlCalendar::getActualMinimum](intlcalendar.getactualminimum) — The minimum value for a field, considering the objectʼs current time * [IntlCalendar::getAvailableLocales](intlcalendar.getavailablelocales) — Get array of locales for which there is data * [IntlCalendar::getDayOfWeekType](intlcalendar.getdayofweektype) — Tell whether a day is a weekday, weekend or a day that has a transition between the two * [IntlCalendar::getErrorCode](intlcalendar.geterrorcode) — Get last error code on the object * [IntlCalendar::getErrorMessage](intlcalendar.geterrormessage) — Get last error message on the object * [IntlCalendar::getFirstDayOfWeek](intlcalendar.getfirstdayofweek) — Get the first day of the week for the calendarʼs locale * [IntlCalendar::getGreatestMinimum](intlcalendar.getgreatestminimum) — Get the largest local minimum value for a field * [IntlCalendar::getKeywordValuesForLocale](intlcalendar.getkeywordvaluesforlocale) — Get set of locale keyword values * [IntlCalendar::getLeastMaximum](intlcalendar.getleastmaximum) — Get the smallest local maximum for a field * [IntlCalendar::getLocale](intlcalendar.getlocale) — Get the locale associated with the object * [IntlCalendar::getMaximum](intlcalendar.getmaximum) — Get the global maximum value for a field * [IntlCalendar::getMinimalDaysInFirstWeek](intlcalendar.getminimaldaysinfirstweek) — Get minimal number of days the first week in a year or month can have * [IntlCalendar::getMinimum](intlcalendar.getminimum) — Get the global minimum value for a field * [IntlCalendar::getNow](intlcalendar.getnow) — Get number representing the current time * [IntlCalendar::getRepeatedWallTimeOption](intlcalendar.getrepeatedwalltimeoption) — Get behavior for handling repeating wall time * [IntlCalendar::getSkippedWallTimeOption](intlcalendar.getskippedwalltimeoption) — Get behavior for handling skipped wall time * [IntlCalendar::getTime](intlcalendar.gettime) — Get time currently represented by the object * [IntlCalendar::getTimeZone](intlcalendar.gettimezone) — Get the objectʼs timezone * [IntlCalendar::getType](intlcalendar.gettype) — Get the calendar type * [IntlCalendar::getWeekendTransition](intlcalendar.getweekendtransition) — Get time of the day at which weekend begins or ends * [IntlCalendar::inDaylightTime](intlcalendar.indaylighttime) — Whether the objectʼs time is in Daylight Savings Time * [IntlCalendar::isEquivalentTo](intlcalendar.isequivalentto) — Whether another calendar is equal but for a different time * [IntlCalendar::isLenient](intlcalendar.islenient) — Whether date/time interpretation is in lenient mode * [IntlCalendar::isSet](intlcalendar.isset) — Whether a field is set * [IntlCalendar::isWeekend](intlcalendar.isweekend) — Whether a certain date/time is in the weekend * [IntlCalendar::roll](intlcalendar.roll) — Add value to field without carrying into more significant fields * [IntlCalendar::set](intlcalendar.set) — Set a time field or several common fields at once * [IntlCalendar::setFirstDayOfWeek](intlcalendar.setfirstdayofweek) — Set the day on which the week is deemed to start * [IntlCalendar::setLenient](intlcalendar.setlenient) — Set whether date/time interpretation is to be lenient * [IntlCalendar::setMinimalDaysInFirstWeek](intlcalendar.setminimaldaysinfirstweek) — Set minimal number of days the first week in a year or month can have * [IntlCalendar::setRepeatedWallTimeOption](intlcalendar.setrepeatedwalltimeoption) — Set behavior for handling repeating wall times at negative timezone offset transitions * [IntlCalendar::setSkippedWallTimeOption](intlcalendar.setskippedwalltimeoption) — Set behavior for handling skipped wall times at positive timezone offset transitions * [IntlCalendar::setTime](intlcalendar.settime) — Set the calendar time in milliseconds since the epoch * [IntlCalendar::setTimeZone](intlcalendar.settimezone) — Set the timezone used by this calendar * [IntlCalendar::toDateTime](intlcalendar.todatetime) — Convert an IntlCalendar into a DateTime object
programming_docs
php EventHttpConnection::setRetries EventHttpConnection::setRetries =============================== (PECL event >= 1.2.6-beta) EventHttpConnection::setRetries — Sets the retry limit for the connection ### Description ``` public EventHttpConnection::setRetries( int $retries ): void ``` Sets the retry limit for the connection ### Parameters `retries` The retry limit. **`-1`** means infinity. ### Return Values No value is returned. php The SoapFault class The SoapFault class =================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Represents a SOAP fault. Class synopsis -------------- class **SoapFault** extends [Exception](class.exception) { /\* Properties \*/ public string [$faultstring](class.soapfault#soapfault.props.faultstring); public ?string [$faultcode](class.soapfault#soapfault.props.faultcode) = null; public ?string [$faultcodens](class.soapfault#soapfault.props.faultcodens) = null; public ?string [$faultactor](class.soapfault#soapfault.props.faultactor) = null; public [mixed](language.types.declarations#language.types.declarations.mixed) [$detail](class.soapfault#soapfault.props.detail) = null; public ?string [$\_name](class.soapfault#soapfault.props.-name) = null; public [mixed](language.types.declarations#language.types.declarations.mixed) [$headerfault](class.soapfault#soapfault.props.headerfault) = null; /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/ public [\_\_construct](soapfault.construct)( array|string|null `$code`, string `$string`, ?string `$actor` = **`null`**, [mixed](language.types.declarations#language.types.declarations.mixed) `$details` = **`null`**, ?string `$name` = **`null`**, [mixed](language.types.declarations#language.types.declarations.mixed) `$headerFault` = **`null`** ) ``` public __toString(): string ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } Properties ---------- \_name detail faultactor faultcode faultcodens faultstring headerfault Table of Contents ----------------- * [SoapFault::\_\_construct](soapfault.construct) — SoapFault constructor * [SoapFault::\_\_toString](soapfault.tostring) — Obtain a string representation of a SoapFault php IntlChar::enumCharTypes IntlChar::enumCharTypes ======================= (PHP 7, PHP 8) IntlChar::enumCharTypes — Enumerate all code points with their Unicode general categories ### Description ``` public static IntlChar::enumCharTypes(callable $callback): void ``` Enumerates efficiently all code points with their Unicode general categories. This is useful for building data structures, for enumerating all assigned code points, etc. For each contiguous range of code points with a given general category ("character type"), the `callback` function is called. Adjacent ranges have different types. The Unicode Standard guarantees that the numeric value of the type is 0..31. ### Parameters `callback` The function that is to be called for each contiguous range of code points with the same general category. The following three arguments will be passed into it: * int `$start` - The starting code point of the range * int `$end` - The ending code point of the range * int `$name` - The category type (one of the `IntlChar::CHAR_CATEGORY_*` constants) ### Return Values No value is returned. ### Examples **Example #1 Enumerating over a sample range of code points** ``` <?php IntlChar::enumCharTypes(function($start, $end, $type) {     printf("U+%04x through U+%04x are in category %d\n", $start, $end, $type); }); ?> ``` The above example will output: ``` U+0000 through U+0020 are in category 15 U+0020 through U+0021 are in category 12 U+0021 through U+0024 are in category 23 U+0024 through U+0025 are in category 25 U+0025 through U+0028 are in category 23 U+0028 through U+0029 are in category 20 U+0029 through U+002a are in category 21 U+002a through U+002b are in category 23 U+002b through U+002c are in category 24 U+002c through U+002d are in category 23 U+002d through U+002e are in category 19 U+002e through U+0030 are in category 23 U+0030 through U+003a are in category 9 ... ``` php IntlChar::getIntPropertyMaxValue IntlChar::getIntPropertyMaxValue ================================ (PHP 7, PHP 8) IntlChar::getIntPropertyMaxValue — Get the max value for a Unicode property ### Description ``` public static IntlChar::getIntPropertyMaxValue(int $property): int ``` Gets the maximum value for an enumerated/integer/binary Unicode property. ### Parameters `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). ### Return Values The maximum value returned by [IntlChar::getIntPropertyValue()](intlchar.getintpropertyvalue) for a Unicode property. `<=0` if the property selector is out of range. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_BIDI_CLASS)); var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_SCRIPT)); var_dump(IntlChar::getIntPropertyMaxValue(IntlChar::PROPERTY_IDEOGRAPHIC)); var_dump(IntlChar::getIntPropertyMaxValue(999999999)); // Some made-up value ?> ``` The above example will output: ``` int(22) int(166) int(1) int(-1) ``` ### See Also * [IntlChar::hasBinaryProperty()](intlchar.hasbinaryproperty) - Check a binary Unicode property for a code point * [IntlChar::getIntPropertyMinValue()](intlchar.getintpropertyminvalue) - Get the min value for a Unicode property * [IntlChar::getIntPropertyValue()](intlchar.getintpropertyvalue) - Get the value for a Unicode property for a code point * [IntlChar::getUnicodeVersion()](intlchar.getunicodeversion) - Get the Unicode version php None Defining namespaces ------------------- (PHP 5 >= 5.3.0, PHP 7, PHP 8) Although any valid PHP code can be contained within a namespace, only the following types of code are affected by namespaces: classes (including abstracts and traits), interfaces, functions and constants. Namespaces are declared using the `namespace` keyword. A file containing a namespace must declare the namespace at the top of the file before any other code - with one exception: the [declare](control-structures.declare) keyword. **Example #1 Declaring a single namespace** ``` <?php namespace MyProject; const CONNECT_OK = 1; class Connection { /* ... */ } function connect() { /* ... */ } ?> ``` > **Note**: Fully qualified names (i.e. names starting with a backslash) are not allowed in namespace declarations, because such constructs are interpreted as relative namespace expressions. > > The only code construct allowed before a namespace declaration is the `declare` statement, for defining encoding of a source file. In addition, no non-PHP code may precede a namespace declaration, including extra whitespace: **Example #2 Declaring a single namespace** ``` <html> <?php namespace MyProject; // fatal error - namespace must be the first statement in the script ?> ``` In addition, unlike any other PHP construct, the same namespace may be defined in multiple files, allowing splitting up of a namespace's contents across the filesystem. php The DOMNode class The DOMNode class ================= Class synopsis -------------- (PHP 5, PHP 7, PHP 8) class **DOMNode** { /\* Properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ ``` public appendChild(DOMNode $node): DOMNode|false ``` ``` public C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public cloneNode(bool $deep = false): DOMNode|false ``` ``` public getLineNo(): int ``` ``` public getNodePath(): ?string ``` ``` public hasAttributes(): bool ``` ``` public hasChildNodes(): bool ``` ``` public insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public isDefaultNamespace(string $namespace): bool ``` ``` public isSameNode(DOMNode $otherNode): bool ``` ``` public isSupported(string $feature, string $version): bool ``` ``` public lookupNamespaceUri(string $prefix): string ``` ``` public lookupPrefix(string $namespace): ?string ``` ``` public normalize(): void ``` ``` public removeChild(DOMNode $child): DOMNode|false ``` ``` public replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- nodeName Returns the most accurate name for the current node type nodeValue The value of this node, depending on its type. Contrary to the W3C specification, the node value of [DOMElement](class.domelement) nodes is equal to [DOMNode::textContent](class.domnode#domnode.props.textcontent) instead of **`null`**. nodeType Gets the type of the node. One of the predefined [XML\_xxx\_NODE constants](https://www.php.net/manual/en/dom.constants.php) parentNode The parent of this node. If there is no such node, this returns **`null`**. childNodes A [DOMNodeList](class.domnodelist) that contains all children of this node. If there are no children, this is an empty [DOMNodeList](class.domnodelist). firstChild The first child of this node. If there is no such node, this returns **`null`**. lastChild The last child of this node. If there is no such node, this returns **`null`**. previousSibling The node immediately preceding this node. If there is no such node, this returns **`null`**. nextSibling The node immediately following this node. If there is no such node, this returns **`null`**. attributes A [DOMNamedNodeMap](class.domnamednodemap) containing the attributes of this node (if it is a [DOMElement](class.domelement)) or **`null`** otherwise. ownerDocument The [DOMDocument](class.domdocument) object associated with this node, or **`null`** if this node is a [DOMDocument](class.domdocument) namespaceURI The namespace URI of this node, or **`null`** if it is unspecified. prefix The namespace prefix of this node. localName Returns the local part of the qualified name of this node. baseURI The absolute base URI of this node or **`null`** if the implementation wasn't able to obtain an absolute URI. textContent The text content of this node and its descendants. Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The unimplemented methods **DOMNode::compareDocumentPosition()**, **DOMNode::isEqualNode()**, **DOMNode::getFeature()**, **DOMNode::setUserData()** and **DOMNode::getUserData()** have been removed. | Notes ----- > > **Note**: > > > The DOM extension uses UTF-8 encoding. Use [mb\_convert\_encoding()](function.mb-convert-encoding), [UConverter::transcode()](uconverter.transcode), or [iconv()](function.iconv) to handle other encodings. > > > See Also -------- * [» W3C specification of Node](http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1950641247) Table of Contents ----------------- * [DOMNode::appendChild](domnode.appendchild) — Adds new child at the end of the children * [DOMNode::C14N](domnode.c14n) — Canonicalize nodes to a string * [DOMNode::C14NFile](domnode.c14nfile) — Canonicalize nodes to a file * [DOMNode::cloneNode](domnode.clonenode) — Clones a node * [DOMNode::getLineNo](domnode.getlineno) — Get line number for a node * [DOMNode::getNodePath](domnode.getnodepath) — Get an XPath for a node * [DOMNode::hasAttributes](domnode.hasattributes) — Checks if node has attributes * [DOMNode::hasChildNodes](domnode.haschildnodes) — Checks if node has children * [DOMNode::insertBefore](domnode.insertbefore) — Adds a new child before a reference node * [DOMNode::isDefaultNamespace](domnode.isdefaultnamespace) — Checks if the specified namespaceURI is the default namespace or not * [DOMNode::isSameNode](domnode.issamenode) — Indicates if two nodes are the same node * [DOMNode::isSupported](domnode.issupported) — Checks if feature is supported for specified version * [DOMNode::lookupNamespaceUri](domnode.lookupnamespaceuri) — Gets the namespace URI of the node based on the prefix * [DOMNode::lookupPrefix](domnode.lookupprefix) — Gets the namespace prefix of the node based on the namespace URI * [DOMNode::normalize](domnode.normalize) — Normalizes the node * [DOMNode::removeChild](domnode.removechild) — Removes child from list of children * [DOMNode::replaceChild](domnode.replacechild) — Replaces a child php DOMText::__construct DOMText::\_\_construct ====================== (PHP 5, PHP 7, PHP 8) DOMText::\_\_construct — Creates a new [DOMText](class.domtext) object ### Description public **DOMText::\_\_construct**(string `$data` = "") Creates a new [DOMText](class.domtext) object. ### Parameters `data` The value of the text node. If not supplied an empty text node is created. ### Examples **Example #1 Creating a new DOMText** ``` <?php $dom = new DOMDocument('1.0', 'iso-8859-1'); $element = $dom->appendChild(new DOMElement('root')); $text = $element->appendChild(new DOMText('root value')); echo $dom->saveXML(); /* <?xml version="1.0" encoding="iso-8859-1"?><root>root value</root> */ ?> ``` ### See Also * [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node php SplFileObject::ftell SplFileObject::ftell ==================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::ftell — Return current file position ### Description ``` public SplFileObject::ftell(): int|false ``` Returns the position of the file pointer which represents the current offset in the file stream. ### Parameters This function has no parameters. ### Return Values Returns the position of the file pointer as an integer, or **`false`** on error. ### Examples **Example #1 **SplFileObject::ftell()** example** ``` <?php $file = new SplFileObject("/etc/passwd"); // Read first line $data = $file->fgets(); // Where are we? echo $file->ftell(); ?> ``` ### See Also * [ftell()](function.ftell) - Returns the current position of the file read/write pointer php radius_send_request radius\_send\_request ===================== (PECL radius >= 1.1.0) radius\_send\_request — Sends the request and waits for a reply ### Description ``` radius_send_request(resource $radius_handle): int ``` After the Radius request has been constructed, it is sent by **radius\_send\_request()**. The **radius\_send\_request()** function sends the request and waits for a valid reply, retrying the defined servers in round-robin fashion as necessary. ### Parameters `radius_handle` The RADIUS resource. ### Return Values If a valid response is received, **radius\_send\_request()** returns the Radius code which specifies the type of the response. This will typically be **`RADIUS_ACCESS_ACCEPT`**, **`RADIUS_ACCESS_REJECT`**, or **`RADIUS_ACCESS_CHALLENGE`**. If no valid response is received, **radius\_send\_request()** returns **`false`**. ### See Also * [radius\_create\_request()](function.radius-create-request) - Create accounting or authentication request php Ev::feedSignal Ev::feedSignal ============== (PECL ev >= 0.2.0) Ev::feedSignal — Feed a signal event info Ev ### Description ``` final public static Ev::feedSignal( int $signum ): void ``` Simulates a signal receive. It is safe to call this function at any time, from any context, including signal handlers or random threads. Its main use is to customise signal handling in the process. Unlike [Ev::feedSignalEvent()](ev.feedsignalevent) , this works regardless of which loop has registered the signal. ### Parameters `signum` Signal number. See `signal(7)` man page for detals. You can use constants exported by `pcntl` extension. ### Return Values No value is returned. ### See Also * [Ev::feedSignalEvent()](ev.feedsignalevent) - Feed signal event into the default loop php QuickHashIntStringHash::delete QuickHashIntStringHash::delete ============================== (PECL quickhash >= Unknown) QuickHashIntStringHash::delete — This method deletes an entry from the hash ### Description ``` public QuickHashIntStringHash::delete(int $key): bool ``` This method deletes an entry from the hash, and returns whether the entry was deleted or not. Associated memory structures will not be freed immediately, but rather when the hash itself is freed. Elements can not be deleted when the hash is used in an iterator. The method will not throw an exception, but simply return **`false`** like would happen with any other deletion failure. ### Parameters `key` The key of the entry to delete. ### Return Values **`true`** when the entry was deleted, and **`false`** if the entry was not deleted. ### Examples **Example #1 **QuickHashIntStringHash::delete()** example** ``` <?php $hash = new QuickHashIntStringHash( 1024 ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->add( 4, "five" ) ); var_dump( $hash->delete( 4 ) ); var_dump( $hash->exists( 4 ) ); var_dump( $hash->delete( 4 ) ); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) bool(true) bool(false) bool(false) ``` php Imagick::encipherImage Imagick::encipherImage ====================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::encipherImage — Enciphers an image ### Description ``` public Imagick::encipherImage(string $passphrase): bool ``` Converts plain pixels to enciphered pixels. The image is not readable until it has been deciphered using [Imagick::decipherImage()](imagick.decipherimage) This method is available if Imagick has been compiled against ImageMagick version 6.3.9 or newer. ### Parameters `passphrase` The passphrase ### Return Values Returns **`true`** on success. ### See Also * [Imagick::decipherImage()](imagick.decipherimage) - Deciphers an image
programming_docs
php RecursiveTreeIterator::key RecursiveTreeIterator::key ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::key — Get the key of the current element ### Description ``` public RecursiveTreeIterator::key(): mixed ``` Gets the current key prefixed and postfixed. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns the current key prefixed and postfixed. php gmstrftime gmstrftime ========== (PHP 4, PHP 5, PHP 7, PHP 8) gmstrftime — Format a GMT/UTC time/date according to locale settings **Warning**This function has been *DEPRECATED* as of PHP 8.1.0. Relying on this function is highly discouraged. Alternatives to this function include: * [gmdate()](function.gmdate) * [IntlDateFormatter::format()](intldateformatter.format) ### Description ``` gmstrftime(string $format, ?int $timestamp = null): string|false ``` Behaves the same as [strftime()](function.strftime) except that the time returned is Greenwich Mean Time (GMT). For example, when run in Eastern Standard Time (GMT -0500), the first line below prints "Dec 31 1998 20:00:00", while the second prints "Jan 01 1999 01:00:00". **Warning** This function depends on operating system locale information, which might be inconsistent with each other, or not available at all. Instead use the [IntlDateFormatter::format()](intldateformatter.format) method. ### Parameters `format` See description in [strftime()](function.strftime). `timestamp` The optional `timestamp` parameter is an int Unix timestamp that defaults to the current local time if `timestamp` is omitted or **`null`**. In other words, it defaults to the value of [time()](function.time). ### Return Values Returns a string formatted according to the given format string using the given `timestamp` or the current local time if no timestamp is given. Month and weekday names and other language dependent strings respect the current locale set with [setlocale()](function.setlocale). On failure, **`false`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `timestamp` is nullable now. | ### Examples **Example #1 **gmstrftime()** example** ``` <?php setlocale(LC_TIME, 'en_US'); echo strftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n"; echo gmstrftime("%b %d %Y %H:%M:%S", mktime(20, 0, 0, 12, 31, 98)) . "\n"; ?> ``` ### See Also * [IntlDateFormatter::format()](intldateformatter.format) - Format the date/time value as a string * [DateTimeInterface::format()](datetime.format) - Returns date formatted according to given format * [strftime()](function.strftime) - Format a local time/date according to locale settings php None Recursive patterns ------------------ Consider the problem of matching a string in parentheses, allowing for unlimited nested parentheses. Without the use of recursion, the best that can be done is to use a pattern that matches up to some fixed depth of nesting. It is not possible to handle an arbitrary nesting depth. Perl 5.6 has provided an experimental facility that allows regular expressions to recurse (among other things). The special item (?R) is provided for the specific case of recursion. This PCRE pattern solves the parentheses problem (assume the [PCRE\_EXTENDED](reference.pcre.pattern.modifiers) option is set so that white space is ignored): `\( ( (?>[^()]+) | (?R) )* \)` First it matches an opening parenthesis. Then it matches any number of substrings which can either be a sequence of non-parentheses, or a recursive match of the pattern itself (i.e. a correctly parenthesized substring). Finally there is a closing parenthesis. This particular example pattern contains nested unlimited repeats, and so the use of a once-only subpattern for matching strings of non-parentheses is important when applying the pattern to strings that do not match. For example, when it is applied to `(aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()` it yields "no match" quickly. However, if a once-only subpattern is not used, the match runs for a very long time indeed because there are so many different ways the + and \* repeats can carve up the subject, and all have to be tested before failure can be reported. The values set for any capturing subpatterns are those from the outermost level of the recursion at which the subpattern value is set. If the pattern above is matched against `(ab(cd)ef)` the value for the capturing parentheses is "ef", which is the last value taken on at the top level. If additional parentheses are added, giving `\( ( ( (?>[^()]+) | (?R) )* ) \)` then the string they capture is "ab(cd)ef", the contents of the top level parentheses. If there are more than 15 capturing parentheses in a pattern, PCRE has to obtain extra memory to store data during a recursion, which it does by using pcre\_malloc, freeing it via pcre\_free afterwards. If no memory can be obtained, it saves data for the first 15 capturing parentheses only, as there is no way to give an out-of-memory error from within a recursion. `(?1)`, `(?2)` and so on can be used for recursive subpatterns too. It is also possible to use named subpatterns: `(?P>name)` or `(?&name)`. If the syntax for a recursive subpattern reference (either by number or by name) is used outside the parentheses to which it refers, it operates like a subroutine in a programming language. An earlier example pointed out that the pattern `(sens|respons)e and \1ibility` matches "sense and sensibility" and "response and responsibility", but not "sense and responsibility". If instead the pattern `(sens|respons)e and (?1)ibility` is used, it does match "sense and responsibility" as well as the other two strings. Such references must, however, follow the subpattern to which they refer. The maximum length of a subject string is the largest positive number that an integer variable can hold. However, PCRE uses recursion to handle subpatterns and indefinite repetition. This means that the available stack space may limit the size of a subject string that can be processed by certain patterns. php ReflectionEnum::getBackingType ReflectionEnum::getBackingType ============================== (PHP 8 >= 8.1.0) ReflectionEnum::getBackingType — Gets the backing type of an Enum, if any ### Description ``` public ReflectionEnum::getBackingType(): ?ReflectionNamedType ``` If the enumeration is a Backed Enum, this method will return an instance of [ReflectionType](class.reflectiontype) for the backing type of the Enum. If it is not a Backed Enum, it will return `null`. ### Parameters This function has no parameters. ### Return Values An instance of [ReflectionNamedType](class.reflectionnamedtype), or `null` if the Enum has no backing type. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | The return type is now declared as `?ReflectionNamedType`. Previously, `?ReflectionType` was declared. | ### Examples **Example #1 **ReflectionEnum::getBackingType()** example** ``` <?php enum Suit: string {     case Hearts = 'H';     case Diamonds = 'D';     case Clubs = 'C';     case Spades = 'S'; } $rEnum = new ReflectionEnum(Suit::class); $rBackingType = $rEnum->getBackingType(); var_dump((string)$rBackingType); ?> ``` The above example will output: ``` string(6) "string" ``` ### See Also * [Enumerations](https://www.php.net/manual/en/language.enumerations.php) * [ReflectionEnum::isBacked()](reflectionenum.isbacked) - Determines if an Enum is a Backed Enum php Imagick::getImagePage Imagick::getImagePage ===================== (PECL imagick 2, PECL imagick 3) Imagick::getImagePage — Returns the page geometry ### Description ``` public Imagick::getImagePage(): array ``` Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y". ### Parameters This function has no parameters. ### Return Values Returns the page geometry associated with the image in an array with the keys "width", "height", "x", and "y". ### Errors/Exceptions Throws ImagickException on error. php Imagick::queryFonts Imagick::queryFonts =================== (PECL imagick 2, PECL imagick 3) Imagick::queryFonts — Returns the configured fonts ### Description ``` public static Imagick::queryFonts(string $pattern = "*"): array ``` Returns the configured fonts. ### Parameters `pattern` The query pattern ### Return Values Returns an array containing the configured fonts. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::queryFonts()**** ``` <?php         $output = '';         $output .= "Fonts that match 'Helvetica*' are:<br/>";         $fontList = \Imagick::queryFonts("Helvetica*");           foreach ($fontList as $fontName) {             $output .= '<li>'. $fontName."</li>";         }         return $output; ?> ``` php The SplStack class The SplStack class ================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) The SplStack class provides the main functionalities of a stack implemented using a doubly linked list. Class synopsis -------------- class **SplStack** extends [SplDoublyLinkedList](class.spldoublylinkedlist) { /\* Inherited constants \*/ public const int [SplDoublyLinkedList::IT\_MODE\_LIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-lifo); public const int [SplDoublyLinkedList::IT\_MODE\_FIFO](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-fifo); public const int [SplDoublyLinkedList::IT\_MODE\_DELETE](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-delete); public const int [SplDoublyLinkedList::IT\_MODE\_KEEP](class.spldoublylinkedlist#spldoublylinkedlist.constants.it-mode-keep); /\* Methods \*/ public [\_\_construct](splstack.construct)() ``` public setIteratorMode(int $mode): void ``` /\* Inherited methods \*/ ``` public SplDoublyLinkedList::add(int $index, mixed $value): void ``` ``` public SplDoublyLinkedList::bottom(): mixed ``` ``` public SplDoublyLinkedList::count(): int ``` ``` public SplDoublyLinkedList::current(): mixed ``` ``` public SplDoublyLinkedList::getIteratorMode(): int ``` ``` public SplDoublyLinkedList::isEmpty(): bool ``` ``` public SplDoublyLinkedList::key(): int ``` ``` public SplDoublyLinkedList::next(): void ``` ``` public SplDoublyLinkedList::offsetExists(int $index): bool ``` ``` public SplDoublyLinkedList::offsetGet(int $index): mixed ``` ``` public SplDoublyLinkedList::offsetSet(?int $index, mixed $value): void ``` ``` public SplDoublyLinkedList::offsetUnset(int $index): void ``` ``` public SplDoublyLinkedList::pop(): mixed ``` ``` public SplDoublyLinkedList::prev(): void ``` ``` public SplDoublyLinkedList::push(mixed $value): void ``` ``` public SplDoublyLinkedList::rewind(): void ``` ``` public SplDoublyLinkedList::serialize(): string ``` ``` public SplDoublyLinkedList::setIteratorMode(int $mode): int ``` ``` public SplDoublyLinkedList::shift(): mixed ``` ``` public SplDoublyLinkedList::top(): mixed ``` ``` public SplDoublyLinkedList::unserialize(string $data): void ``` ``` public SplDoublyLinkedList::unshift(mixed $value): void ``` ``` public SplDoublyLinkedList::valid(): bool ``` } Table of Contents ----------------- * [SplStack::\_\_construct](splstack.construct) — Constructs a new stack implemented using a doubly linked list * [SplStack::setIteratorMode](splstack.setiteratormode) — Sets the mode of iteration php SolrQuery::setHighlightMergeContiguous SolrQuery::setHighlightMergeContiguous ====================================== (PECL solr >= 0.9.2) SolrQuery::setHighlightMergeContiguous — Whether or not to collapse contiguous fragments into a single fragment ### Description ``` public SolrQuery::setHighlightMergeContiguous(bool $flag, string $field_override = ?): SolrQuery ``` Whether or not to collapse contiguous fragments into a single fragment ### Parameters `value` Whether or not to collapse contiguous fragments into a single fragment `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php array_search array\_search ============= (PHP 4 >= 4.0.5, PHP 5, PHP 7, PHP 8) array\_search — Searches the array for a given value and returns the first corresponding key if successful ### Description ``` array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false ``` Searches for `needle` in `haystack`. ### Parameters `needle` The searched value. > > **Note**: > > > If `needle` is a string, the comparison is done in a case-sensitive manner. > > `haystack` The array. `strict` If the third parameter `strict` is set to **`true`** then the **array\_search()** function will search for *identical* elements in the `haystack`. This means it will also perform a [strict type comparison](https://www.php.net/manual/en/language.types.php) of the `needle` in the `haystack`, and objects must be the same instance. ### Return Values Returns the key for `needle` if it is found in the array, **`false`** otherwise. If `needle` is found in `haystack` more than once, the first matching key is returned. To return the keys for all matching values, use [array\_keys()](function.array-keys) with the optional `search_value` parameter instead. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Examples **Example #1 **array\_search()** example** ``` <?php $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); $key = array_search('green', $array); // $key = 2; $key = array_search('red', $array);   // $key = 1; ?> ``` ### See Also * [array\_keys()](function.array-keys) - Return all the keys or a subset of the keys of an array * [array\_values()](function.array-values) - Return all the values of an array * [array\_key\_exists()](function.array-key-exists) - Checks if the given key or index exists in the array * [in\_array()](function.in-array) - Checks if a value exists in an array php imagesetstyle imagesetstyle ============= (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagesetstyle — Set the style for line drawing ### Description ``` imagesetstyle(GdImage $image, array $style): bool ``` **imagesetstyle()** sets the style to be used by all line drawing functions (such as [imageline()](function.imageline) and [imagepolygon()](function.imagepolygon)) when drawing with the special color **`IMG_COLOR_STYLED`** or lines of images with color **`IMG_COLOR_STYLEDBRUSHED`**. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `style` An array of pixel colors. You can use the **`IMG_COLOR_TRANSPARENT`** constant to add a transparent pixel. Note that `style` must not be an empty array. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples Following example script draws a dashed line from upper left to lower right corner of the canvas: **Example #1 **imagesetstyle()** example** ``` <?php header("Content-type: image/jpeg"); $im  = imagecreatetruecolor(100, 100); $w   = imagecolorallocate($im, 255, 255, 255); $red = imagecolorallocate($im, 255, 0, 0); /* Draw a dashed line, 5 red pixels, 5 white pixels */ $style = array($red, $red, $red, $red, $red, $w, $w, $w, $w, $w); imagesetstyle($im, $style); imageline($im, 0, 0, 100, 100, IMG_COLOR_STYLED); /* Draw a line of happy faces using imagesetbrush() with imagesetstyle */ $style = array($w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $w, $red); imagesetstyle($im, $style); $brush = imagecreatefrompng("http://www.libpng.org/pub/png/images/smile.happy.png"); $w2 = imagecolorallocate($brush, 255, 255, 255); imagecolortransparent($brush, $w2); imagesetbrush($im, $brush); imageline($im, 100, 0, 0, 100, IMG_COLOR_STYLEDBRUSHED); imagejpeg($im); imagedestroy($im); ?> ``` The above example will output something similar to: ### See Also * [imagesetbrush()](function.imagesetbrush) - Set the brush image for line drawing * [imageline()](function.imageline) - Draw a line php DOMProcessingInstruction::__construct DOMProcessingInstruction::\_\_construct ======================================= (PHP 5, PHP 7, PHP 8) DOMProcessingInstruction::\_\_construct — Creates a new [DOMProcessingInstruction](class.domprocessinginstruction) object ### Description public **DOMProcessingInstruction::\_\_construct**(string `$name`, string `$value` = "") Creates a new [DOMProcessingInstruction](class.domprocessinginstruction) object. This object is read only. It may be appended to a document, but additional nodes may not be appended to this node until the node is associated with a document. To create a writeable node, use [DOMDocument::createProcessingInstruction](domdocument.createprocessinginstruction). ### Parameters `name` The tag name of the processing instruction. `value` The value of the processing instruction. ### Examples **Example #1 Creating a new [DOMProcessingInstruction](class.domprocessinginstruction) object** ``` <?php $dom = new DOMDocument('1.0', 'UTF-8'); $html = $dom->appendChild(new DOMElement('html')); $body = $html->appendChild(new DOMElement('body')); $pinode = new DOMProcessingInstruction('php', 'echo "Hello World"; '); $body->appendChild($pinode); echo $dom->saveXML();  ?> ``` The above example will output: ``` <?xml version="1.0" encoding="UTF-8"?> <html><body><?php echo "Hello World"; ?></body></html> ``` ### See Also * [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node php eio_set_max_poll_time eio\_set\_max\_poll\_time ========================= (PECL eio >= 0.0.1dev) eio\_set\_max\_poll\_time — Set maximum poll time ### Description ``` eio_set_max_poll_time(float $nseconds): void ``` Polling stops, if poll took longer than `nseconds` seconds. ### Parameters `nseconds` Number of seconds ### Return Values No value is returned. php sodium_crypto_pwhash_str_verify sodium\_crypto\_pwhash\_str\_verify =================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_pwhash\_str\_verify — Verifies that a password matches a hash ### Description ``` sodium_crypto_pwhash_str_verify(string $hash, string $password): bool ``` Checks that a password hash created using [sodium\_crypto\_pwhash\_str()](function.sodium-crypto-pwhash-str) matches a given plain-text password. Note that the parameters are in the opposite order to the same parameters in the similar [password\_verify()](function.password-verify) function. ### Parameters `hash` A hash created by [password\_hash()](function.password-hash). `password` The user's password. ### Return Values Returns **`true`** if the password and hash match, or **`false`** otherwise. ### Notes > > **Note**: > > > Hashes are calculated using the Argon2ID algorithm, providing resistance to both GPU and side-channel attacks. > > ### See Also * [sodium\_crypto\_pwhash\_str()](function.sodium-crypto-pwhash-str) - Get an ASCII-encoded hash * [password\_hash()](function.password-hash) - Creates a password hash * [password\_verify()](function.password-verify) - Verifies that a password matches a hash
programming_docs
php SolrQuery::removeMltQueryField SolrQuery::removeMltQueryField ============================== (PECL solr >= 0.9.2) SolrQuery::removeMltQueryField — Removes one of the moreLikeThis query fields ### Description ``` public SolrQuery::removeMltQueryField(string $queryField): SolrQuery ``` Removes one of the moreLikeThis query fields. ### Parameters `queryField` The query field ### Return Values Returns the current SolrQuery object, if the return value is used. php GearmanClient::doBackground GearmanClient::doBackground =========================== (PECL gearman >= 0.5.0) GearmanClient::doBackground — Run a task in the background ### Description ``` public GearmanClient::doBackground(string $function_name, string $workload, string $unique = ?): string ``` Runs a task in the background, returning a job handle which can be used to get the status of the running task. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `unique` A unique ID used to identify a particular task ### Return Values The job handle for the submitted task. ### Examples **Example #1 Submit and monitor a background job** The worker in this example has an artificial delay introduced to mimic a long running job. The client script periodically checks the status of the running job. ``` <?php /* create our object */ $gmclient= new GearmanClient(); /* add the default server */ $gmclient->addServer(); /* run reverse client */ $job_handle = $gmclient->doBackground("reverse", "this is a test"); if ($gmclient->returnCode() != GEARMAN_SUCCESS) {   echo "bad return code\n";   exit; } $done = false; do {    sleep(3);    $stat = $gmclient->jobStatus($job_handle);    if (!$stat[0]) // the job is known so it is not done       $done = true;    echo "Running: " . ($stat[1] ? "true" : "false") . ", numerator: " . $stat[2] . ", denominator: " . $stat[3] . "\n"; } while(!$done); echo "done!\n"; ?> ``` The above example will output something similar to: ``` Running: true, numerator: 3, denominator: 14 Running: true, numerator: 6, denominator: 14 Running: true, numerator: 9, denominator: 14 Running: true, numerator: 12, denominator: 14 Running: false, numerator: 0, denominator: 0 done! ``` ### See Also * [GearmanClient::doNormal()](gearmanclient.donormal) - Run a single task and return a result * [GearmanClient::doHigh()](gearmanclient.dohigh) - Run a single high priority task * [GearmanClient::doLow()](gearmanclient.dolow) - Run a single low priority task * [GearmanClient::doHighBackground()](gearmanclient.dohighbackground) - Run a high priority task in the background * [GearmanClient::doLowBackground()](gearmanclient.dolowbackground) - Run a low priority task in the background php ZipArchive::unchangeArchive ZipArchive::unchangeArchive =========================== (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.1.0) ZipArchive::unchangeArchive — Revert all global changes done in the archive ### Description ``` public ZipArchive::unchangeArchive(): bool ``` Revert all global changes to the archive. For now, this only reverts archive comment changes. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php solr_get_version solr\_get\_version ================== (PECL solr >= 0.9.1) solr\_get\_version — Returns the current version of the Apache Solr extension ### Description ``` solr_get_version(): string ``` This function returns the current version of the extension as a string. ### Parameters This function has no parameters. ### Return Values It returns a string on success and **`false`** on failure. ### Errors/Exceptions This function throws no errors or exceptions. ### Examples **Example #1 **solr\_get\_version()** example** ``` <?php $solr_version = solr_get_version(); print $solr_version; ?> ``` The above example will output something similar to: ``` 0.9.6 ``` ### See Also * [SolrUtils::getSolrVersion()](solrutils.getsolrversion) - Returns the current version of the Solr extension php ImagickPixelIterator::getNextIteratorRow ImagickPixelIterator::getNextIteratorRow ======================================== (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::getNextIteratorRow — Returns the next row of the pixel iterator ### Description ``` public ImagickPixelIterator::getNextIteratorRow(): array ``` **Warning**This function is currently not documented; only its argument list is available. Returns the next row as an array of pixel wands from the pixel iterator. ### Return Values Returns the next row as an array of ImagickPixel objects, throwing ImagickPixelIteratorException on error. ### Examples **Example #1 **ImagickPixelIterator::getNextIteratorRow()**** ``` <?php function getNextIteratorRow($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imageIterator = $imagick->getPixelIterator();     $count = 0;     while ($pixels = $imageIterator->getNextIteratorRow()) {         if (($count % 3) == 0) {             /* Loop through the pixels in the row (columns) */             foreach ($pixels as $column => $pixel) {                  /** @var $pixel \ImagickPixel */                 if ($column % 2) {                     /* Paint every second pixel black*/                     $pixel->setColor("rgba(0, 0, 0, 0)");                 }             }             /* Sync the iterator, this is important to do on each iteration */             $imageIterator->syncIterator();          }         $count += 1;     }     header("Content-Type: image/jpg");     echo $imagick; } ?> ``` php ReflectionMethod::isAbstract ReflectionMethod::isAbstract ============================ (PHP 5, PHP 7, PHP 8) ReflectionMethod::isAbstract — Checks if method is abstract ### Description ``` public ReflectionMethod::isAbstract(): bool ``` Checks if the method is abstract. ### Parameters This function has no parameters. ### Return Values **`true`** if the method is abstract, otherwise **`false`** ### See Also * [ReflectionMethod::getDeclaringClass()](reflectionmethod.getdeclaringclass) - Gets declaring class for the reflected method php Memcached::replaceByKey Memcached::replaceByKey ======================= (PECL memcached >= 0.1.0) Memcached::replaceByKey — Replace the item under an existing key on a specific server ### Description ``` public Memcached::replaceByKey( string $server_key, string $key, mixed $value, int $expiration = ? ): bool ``` **Memcached::replaceByKey()** is functionally equivalent to [Memcached::replace()](memcached.replace), except that the free-form `server_key` can be used to map the `key` to a specific server. This is useful if you need to keep a bunch of related keys on a certain server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key under which to store the value. `value` The value to store. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key does not exist. ### See Also * [Memcached::replace()](memcached.replace) - Replace the item under an existing key * [Memcached::set()](memcached.set) - Store an item * [Memcached::add()](memcached.add) - Add an item under a new key php eio_nready eio\_nready =========== (PECL eio >= 0.0.1dev) eio\_nready — Returns number of not-yet handled requests ### Description ``` eio_nready(): int ``` ### Parameters This function has no parameters. ### Return Values **eio\_nready()** returns number of not-yet handled requests ### See Also * [eio\_nreqs()](function.eio-nreqs) - Returns number of requests to be processed * **eio\_nready()** * [eio\_nthreads()](function.eio-nthreads) - Returns number of threads currently in use php ReflectionClass::hasConstant ReflectionClass::hasConstant ============================ (PHP 5 >= 5.1.2, PHP 7, PHP 8) ReflectionClass::hasConstant — Checks if constant is defined ### Description ``` public ReflectionClass::hasConstant(string $name): bool ``` Checks whether the class has a specific constant defined or not. ### Parameters `name` The name of the constant being checked for. ### Return Values **`true`** if the constant is defined, otherwise **`false`**. ### Examples **Example #1 **ReflectionClass::hasConstant()** example** ``` <?php class Foo {     const c1 = 1; } $class = new ReflectionClass("Foo"); var_dump($class->hasConstant("c1")); var_dump($class->hasConstant("c2")); ?> ``` The above example will output something similar to: ``` bool(true) bool(false) ``` ### See Also * [ReflectionClass::hasMethod()](reflectionclass.hasmethod) - Checks if method is defined * [ReflectionClass::hasProperty()](reflectionclass.hasproperty) - Checks if property is defined php Yaf_Request_Abstract::setBaseUri Yaf\_Request\_Abstract::setBaseUri ================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::setBaseUri — Set base URI ### Description ``` public Yaf_Request_Abstract::setBaseUri(string $uir): bool ``` Set base URI, base URI is used when doing routing, in routing phase request URI is used to route a request, while base URI is used to skip the leadding part(base URI) of request URI. That is, if comes a request with request URI a/b/c, then if you set base URI to "a/b", only "/c" will be used in routing phase. > > **Note**: > > > generally, you don't need to set this, Yaf will determine it automatically. > > ### Parameters `uir` base URI ### Return Values bool php ParentIterator::getChildren ParentIterator::getChildren =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) ParentIterator::getChildren — Return the inner iterator's children contained in a ParentIterator ### Description ``` public ParentIterator::getChildren(): ParentIterator ``` Get the inner iterator's children contained in a ParentIterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values An object. php VarnishAdmin::setTimeout VarnishAdmin::setTimeout ======================== (PECL varnish >= 0.8) VarnishAdmin::setTimeout — Set the class timeout configuration param ### Description ``` public VarnishAdmin::setTimeout(int $timeout): void ``` ### Parameters `timeout` Connection timeout configuration parameter. ### Return Values php imagepng imagepng ======== (PHP 4, PHP 5, PHP 7, PHP 8) imagepng — Output a PNG image to either the browser or a file ### Description ``` imagepng( GdImage $image, resource|string|null $file = null, int $quality = -1, int $filters = -1 ): bool ``` Outputs or saves a PNG image from the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `file` The path or an open stream resource (which is automatically closed after this function returns) to save the file to. If not set or **`null`**, the raw image stream will be output directly. > > **Note**: > > > **`null`** is invalid if the `quality` and `filters` arguments are not used. > > `quality` Compression level: from 0 (no compression) to 9. The default (`-1`) uses the zlib compression default. For more information see the [» zlib manual](http://www.zlib.net/manual.html). `filters` Allows reducing the PNG file size. It is a bitmask field which may be set to any combination of the `PNG_FILTER_XXX` constants. **`PNG_NO_FILTER`** or **`PNG_ALL_FILTERS`** may also be used to respectively disable or activate all filters. The default value (`-1`) disables filtering. **Caution** The `filters` parameter is ignored by system libgd. ### Return Values Returns **`true`** on success or **`false`** on failure. **Caution**However, if libgd fails to output the image, this function returns **`true`**. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples ``` <?php $im = imagecreatefrompng("test.png"); header('Content-Type: image/png'); imagepng($im); imagedestroy($im); ?> ``` ### See Also * [imagegif()](function.imagegif) - Output image to browser or file * [imagewbmp()](function.imagewbmp) - Output image to browser or file * [imagejpeg()](function.imagejpeg) - Output image to browser or file * [imagetypes()](function.imagetypes) - Return the image types supported by this PHP build * [imagesavealpha()](function.imagesavealpha) - Whether to retain full alpha channel information when saving images php ReflectionParameter::getClass ReflectionParameter::getClass ============================= (PHP 5, PHP 7, PHP 8) ReflectionParameter::getClass — Get a [ReflectionClass](class.reflectionclass) object for the parameter being reflected or **`null`** **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public ReflectionParameter::getClass(): ?ReflectionClass ``` Gets a [ReflectionClass](class.reflectionclass) object for the parameter being reflected or **`null`**. As of PHP 8.0.0 this function is deprecated and not recommended. Instead, use [ReflectionParameter::getType()](reflectionparameter.gettype) to get the [ReflectionType](class.reflectiontype) of the parameter, then interrogate that object to determine the parameter type. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values A [ReflectionClass](class.reflectionclass) object, or **`null`** if no type is declared, or the declared type is not a class or interface. ### Examples **Example #1 Using the [ReflectionParameter](class.reflectionparameter) class** ``` <?php function foo(Exception $a) { } $functionReflection = new ReflectionFunction('foo'); $parameters = $functionReflection->getParameters(); $aParameter = $parameters[0]; echo $aParameter->getClass()->name; ?> ``` ### See Also * [ReflectionParameter::getDeclaringClass()](reflectionparameter.getdeclaringclass) - Gets declaring class php Memcached::getServerList Memcached::getServerList ======================== (PECL memcached >= 0.1.0) Memcached::getServerList — Get the list of the servers in the pool ### Description ``` public Memcached::getServerList(): array ``` **Memcached::getServerList()** returns the list of all servers that are in its server pool. ### Parameters This function has no parameters. ### Return Values The list of all servers in the server pool. ### Examples **Example #1 **Memcached::getServerList()** example** ``` <?php $m = new Memcached(); $m->addServers(array(     array('mem1.domain.com', 11211, 20),     array('mem2.domain.com', 11311, 80), )); var_dump($m->getServerList()); ?> ``` The above example will output: ``` array(2) { [0]=> array(3) { ["host"]=> string(15) "mem1.domain.com" ["port"]=> int(11211) ["weight"]=> int(20) } [1]=> array(3) { ["host"]=> string(15) "mem2.domain.com" ["port"]=> int(11311) ["weight"]=> int(80) } } ``` php EventUtil::getSocketFd EventUtil::getSocketFd ====================== (PECL event >= 1.7.0) EventUtil::getSocketFd — Returns numeric file descriptor of a socket, or stream ### Description ``` public static EventUtil::getSocketFd( mixed $socket ): int ``` Returns numeric file descriptor of a socket or stream specified by `socket` argument just like the `Event` extension does it internally for all methods accepting socket resource or stream. ### Parameters `socket` Socket resource or stream. ### Return Values Returns numeric file descriptor of a socket, or stream. **EventUtil::getSocketFd()** returns **`false`** in case if it is whether failed to recognize the type of the underlying file, or detected that the file descriptor associated with `socket` is not valid. php Yaf_Request_Simple::get Yaf\_Request\_Simple::get ========================= (Yaf >=1.0.0) Yaf\_Request\_Simple::get — The get purpose ### Description ``` public Yaf_Request_Simple::get(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Gmagick::implodeimage Gmagick::implodeimage ===================== (PECL gmagick >= Unknown) Gmagick::implodeimage — Creates a new image as a copy ### Description ``` public Gmagick::implodeimage(float $radius): mixed ``` Creates a new image that is a copy of an existing one with the image pixels "imploded" by the specified percentage. ### Parameters `radius` The radius of the implode. ### Return Values Returns imploded [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Yaf_Config_Simple::__construct Yaf\_Config\_Simple::\_\_construct ================================== (Yaf >=1.0.0) Yaf\_Config\_Simple::\_\_construct — The \_\_construct purpose ### Description public **Yaf\_Config\_Simple::\_\_construct**(array `$configs`, bool `$readonly` = false) **Warning**This function is currently not documented; only its argument list is available. ### Parameters `configs` `readonly` ### Return Values php dba_exists dba\_exists =========== (PHP 4, PHP 5, PHP 7, PHP 8) dba\_exists — Check whether key exists ### Description ``` dba_exists(string|array $key, resource $dba): bool ``` **dba\_exists()** checks whether the specified `key` exists in the database. ### Parameters `key` The key the check is performed for. `dba` The database handler, returned by [dba\_open()](function.dba-open) or [dba\_popen()](function.dba-popen). ### Return Values Returns **`true`** if the key exists, **`false`** otherwise. ### See Also * [dba\_delete()](function.dba-delete) - Delete DBA entry specified by key * [dba\_fetch()](function.dba-fetch) - Fetch data specified by key * [dba\_insert()](function.dba-insert) - Insert entry * [dba\_replace()](function.dba-replace) - Replace or insert entry php The DOMText class The DOMText class ================= Introduction ------------ (PHP 5, PHP 7, PHP 8) The **DOMText** class inherits from [DOMCharacterData](class.domcharacterdata) and represents the textual content of a [DOMElement](class.domelement) or [DOMAttr](class.domattr). Class synopsis -------------- class **DOMText** extends [DOMCharacterData](class.domcharacterdata) { /\* Properties \*/ public readonly string [$wholeText](class.domtext#domtext.props.wholetext); /\* Inherited properties \*/ public string [$data](class.domcharacterdata#domcharacterdata.props.data); public readonly int [$length](class.domcharacterdata#domcharacterdata.props.length); public readonly ?[DOMElement](class.domelement) [$previousElementSibling](class.domcharacterdata#domcharacterdata.props.previouselementsibling); public readonly ?[DOMElement](class.domelement) [$nextElementSibling](class.domcharacterdata#domcharacterdata.props.nextelementsibling); public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domtext.construct)(string `$data` = "") ``` public isElementContentWhitespace(): bool ``` ``` public isWhitespaceInElementContent(): bool ``` ``` public splitText(int $offset): DOMText|false ``` /\* Inherited methods \*/ ``` public DOMCharacterData::appendData(string $data): bool ``` ``` public DOMCharacterData::deleteData(int $offset, int $count): bool ``` ``` public DOMCharacterData::insertData(int $offset, string $data): bool ``` ``` public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool ``` ``` public DOMCharacterData::substringData(int $offset, int $count): string|false ``` ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- wholeText Holds all the text of logically-adjacent (not separated by Element, Comment or Processing Instruction) Text nodes. Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The unimplemented method **DOMText::replaceWholeText()** has been removed. | Table of Contents ----------------- * [DOMText::\_\_construct](domtext.construct) — Creates a new DOMText object * [DOMText::isElementContentWhitespace](domtext.iselementcontentwhitespace) — Returns whether this text node contains whitespace in element content * [DOMText::isWhitespaceInElementContent](domtext.iswhitespaceinelementcontent) — Indicates whether this text node contains whitespace * [DOMText::splitText](domtext.splittext) — Breaks this node into two nodes at the specified offset
programming_docs
php Imagick::readImageBlob Imagick::readImageBlob ====================== (PECL imagick 2, PECL imagick 3) Imagick::readImageBlob — Reads image from a binary string ### Description ``` public Imagick::readImageBlob(string $image, string $filename = ?): bool ``` Reads image from a binary string ### Parameters `image` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::readImageBlob()**** ``` <?php function readImageBlob() {     $base64 = "iVBORw0KGgoAAAANSUhEUgAAAM0AAAD  NCAMAAAAsYgRbAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5c  cllPAAAABJQTFRF3NSmzMewPxIG//ncJEJsldTou1jHgAAAARBJREFUeNrs2EEK  gCAQBVDLuv+V20dENbMY831wKz4Y/VHb/5RGQ0NDQ0NDQ0NDQ0NDQ0NDQ  0NDQ0NDQ0NDQ0NDQ0NDQ0NDQ0PzMWtyaGhoaGhoaGhoaGhoaGhoxtb0QGho  aGhoaGhoaGhoaGhoaMbRLEvv50VTQ9OTQ5OpyZ01GpM2g0bfmDQaL7S+ofFC6x  v3ZpxJiywakzbvd9r3RWPS9I2+MWk0+kbf0Hih9Y17U0nTHibrDDQ0NDQ0NDQ0  NDQ0NDQ0NTXbRSL/AK72o6GhoaGhoRlL8951vwsNDQ0NDQ1NDc0WyHtDTEhD  Q0NDQ0NTS5MdGhoaGhoaGhoaGhoaGhoaGhoaGhoaGposzSHAAErMwwQ2HwRQ  AAAAAElFTkSuQmCC";     $imageBlob = base64_decode($base64);     $imagick = new Imagick();     $imagick->readImageBlob($imageBlob);     header("Content-Type: image/png");     echo $imagick; } ?> ``` php IntlChar::digit IntlChar::digit =============== (PHP 7, PHP 8) IntlChar::digit — Get the decimal digit value of a code point for a given radix ### Description ``` public static IntlChar::digit(int|string $codepoint, int $base = 10): int|false|null ``` Returns the decimal digit value of the code point in the specified radix. If the radix is not in the range `2<=radix<=36` or if the value of `codepoint` is not a valid digit in the specified radix, **`false`** is returned. A character is a valid digit if at least one of the following is true: * The character has a decimal digit value. Such characters have the general category "Nd" (decimal digit numbers) and a Numeric\_Type of Decimal. In this case the value is the character's decimal digit value. * The character is one of the uppercase Latin letters 'A' through 'Z'. In this case the value is c-'A'+10. * The character is one of the lowercase Latin letters 'a' through 'z'. In this case the value is ch-'a'+10. * Latin letters from both the ASCII range (0061..007A, 0041..005A) as well as from the Fullwidth ASCII range (FF41..FF5A, FF21..FF3A) are recognized. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) `base` The radix (defaults to `10`). ### Return Values Returns the numeric value represented by the character in the specified radix, or **`false`** if there is no value or if the value exceeds the radix. Returns **`null`** on failure. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::digit("0")); var_dump(IntlChar::digit("3")); var_dump(IntlChar::digit("A")); var_dump(IntlChar::digit("A", 16)); ?> ``` The above example will output: ``` int(0) int(3) bool(false) int(10) ``` ### See Also * [IntlChar::forDigit()](intlchar.fordigit) - Get character representation for a given digit and radix * [IntlChar::charDigitValue()](intlchar.chardigitvalue) - Get the decimal digit value of a decimal digit character * [IntlChar::isdigit()](intlchar.isdigit) - Check if code point is a digit character * **`IntlChar::PROPERTY_NUMERIC_TYPE`** php ibase_affected_rows ibase\_affected\_rows ===================== (PHP 5, PHP 7 < 7.4.0) ibase\_affected\_rows — Return the number of rows that were affected by the previous query ### Description ``` ibase_affected_rows(resource $link_identifier = ?): int ``` This function returns the number of rows that were affected by the previous query (INSERT, UPDATE or DELETE) that was executed from within the specified transaction context. ### Parameters `link_identifier` A transaction context. If `link_identifier` is a connection resource, its default transaction is used. ### Return Values Returns the number of rows as an integer. ### See Also * [ibase\_query()](function.ibase-query) - Execute a query on an InterBase database * [ibase\_execute()](function.ibase-execute) - Execute a previously prepared query php DirectoryIterator::getFilename DirectoryIterator::getFilename ============================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::getFilename — Return file name of current DirectoryIterator item ### Description ``` public DirectoryIterator::getFilename(): string ``` Get the file name of the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values Returns the file name of the current [DirectoryIterator](class.directoryiterator) item. ### Examples **Example #1 A **DirectoryIterator::getFilename()** example** This example will list the contents of the directory containing the script. ``` <?php $dir = new DirectoryIterator(dirname(__FILE__)); foreach ($dir as $fileinfo) {     echo $fileinfo->getFilename() . "\n"; } ?> ``` The above example will output something similar to: ``` . .. apple.jpg banana.jpg index.php pear.jpg ``` ### See Also * [DirectoryIterator::getBasename()](directoryiterator.getbasename) - Get base name of current DirectoryIterator item * [DirectoryIterator::getPath()](directoryiterator.getpath) - Get path of current Iterator item without filename * [DirectoryIterator::getPathname()](directoryiterator.getpathname) - Return path and file name of current DirectoryIterator item * [pathinfo()](function.pathinfo) - Returns information about a file path php Imagick::paintFloodfillImage Imagick::paintFloodfillImage ============================ (PECL imagick 2 >= 2.1.0, PECL imagick 3) Imagick::paintFloodfillImage — Changes the color value of any pixel that matches target **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::paintFloodfillImage( mixed $fill, float $fuzz, mixed $bordercolor, int $x, int $y, int $channel = Imagick::CHANNEL_DEFAULT ): bool ``` Changes the color value of any pixel that matches target and is an immediate neighbor. As of ImageMagick 6.3.8 this method has been deprecated and [Imagick::floodfillPaintImage()](imagick.floodfillpaintimage) should be used instead. ### Parameters `fill` ImagickPixel object or a string containing the fill color `fuzz` The amount of fuzz. For example, set fuzz to 10 and the color red at intensities of 100 and 102 respectively are now interpreted as the same color for the purposes of the floodfill. `bordercolor` ImagickPixel object or a string containing the border color `x` X start position of the floodfill `y` Y start position of the floodfill `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) using bitwise operators. Defaults to **`Imagick::CHANNEL_DEFAULT`**. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel) ### Return Values Returns **`true`** on success. php The ReflectionGenerator class The ReflectionGenerator class ============================= Introduction ------------ (PHP 7, PHP 8) The **ReflectionGenerator** class reports information about a generator. Class synopsis -------------- final class **ReflectionGenerator** { /\* Methods \*/ public [\_\_construct](reflectiongenerator.construct)([Generator](class.generator) `$generator`) ``` public getExecutingFile(): string ``` ``` public getExecutingGenerator(): Generator ``` ``` public getExecutingLine(): int ``` ``` public getFunction(): ReflectionFunctionAbstract ``` ``` public getThis(): ?object ``` ``` public getTrace(int $options = DEBUG_BACKTRACE_PROVIDE_OBJECT): array ``` } Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | The class is final now. | Table of Contents ----------------- * [ReflectionGenerator::\_\_construct](reflectiongenerator.construct) — Constructs a ReflectionGenerator object * [ReflectionGenerator::getExecutingFile](reflectiongenerator.getexecutingfile) — Gets the file name of the currently executing generator * [ReflectionGenerator::getExecutingGenerator](reflectiongenerator.getexecutinggenerator) — Gets the executing Generator object * [ReflectionGenerator::getExecutingLine](reflectiongenerator.getexecutingline) — Gets the currently executing line of the generator * [ReflectionGenerator::getFunction](reflectiongenerator.getfunction) — Gets the function name of the generator * [ReflectionGenerator::getThis](reflectiongenerator.getthis) — Gets the $this value of the generator * [ReflectionGenerator::getTrace](reflectiongenerator.gettrace) — Gets the trace of the executing generator php pg_field_table pg\_field\_table ================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) pg\_field\_table — Returns the name or oid of the tables field ### Description ``` pg_field_table(PgSql\Result $result, int $field, bool $oid_only = false): string|int|false ``` **pg\_field\_table()** returns the name of the table that field belongs to, or the table's oid if `oid_only` is **`true`**. ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `field` Field number, starting from 0. `oid_only` By default the tables name that field belongs to is returned but if `oid_only` is set to **`true`**, then the oid will instead be returned. ### Return Values On success either the fields table name or oid, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Getting table information about a field** ``` <?php $dbconn = pg_connect("dbname=publisher") or die("Could not connect"); $res = pg_query($dbconn, "SELECT bar FROM foo"); echo pg_field_table($res, 0); echo pg_field_table($res, 0, true); $res = pg_query($dbconn, "SELECT version()"); var_dump(pg_field_table($res, 0)); ?> ``` The above example will output something similar to: ``` foo 14379580 bool(false) ``` ### Notes > > **Note**: > > > Returning the oid is much faster than returning the table name because fetching the table name requires a query to the database system table. > > ### See Also * [pg\_field\_name()](function.pg-field-name) - Returns the name of a field * [pg\_field\_type()](function.pg-field-type) - Returns the type name for the corresponding field number php Imagick::shadowImage Imagick::shadowImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::shadowImage — Simulates an image shadow ### Description ``` public Imagick::shadowImage( float $opacity, float $sigma, int $x, int $y ): bool ``` Simulates an image shadow. ### Parameters `opacity` `sigma` `x` `y` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::shadowImage()**** ``` <?php function shadowImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->shadowImage(0.4, 10, 50, 5);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php func_get_arg func\_get\_arg ============== (PHP 4, PHP 5, PHP 7, PHP 8) func\_get\_arg — Return an item from the argument list ### Description ``` func_get_arg(int $position): mixed ``` Gets the specified argument from a user-defined function's argument list. This function may be used in conjunction with [func\_get\_args()](function.func-get-args) and [func\_num\_args()](function.func-num-args) to allow user-defined functions to accept variable-length argument lists. ### Parameters `position` The argument offset. Function arguments are counted starting from zero. ### Return Values Returns the specified argument, or **`false`** on error. ### Errors/Exceptions Generates a warning if called from outside of a user-defined function, or if `position` is greater than the number of arguments actually passed. ### Examples **Example #1 **func\_get\_arg()** example** ``` <?php function foo() {      $numargs = func_num_args();      echo "Number of arguments: $numargs\n";      if ($numargs >= 2) {          echo "Second argument is: " . func_get_arg(1) . "\n";      } } foo(1, 2, 3); ?> ``` The above example will output: ``` Number of arguments: 3 Second argument is: 2 ``` **Example #2 **func\_get\_arg()** example of byref and byval arguments** ``` <?php function byVal($arg) {     echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;     $arg = 'baz';     echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL; } function byRef(&$arg) {     echo 'As passed     : ', var_export(func_get_arg(0)), PHP_EOL;     $arg = 'baz';     echo 'After change  : ', var_export(func_get_arg(0)), PHP_EOL; } $arg = 'bar'; byVal($arg); byRef($arg); ?> ``` The above example will output: As passed : 'bar' After change : 'baz' As passed : 'bar' After change : 'baz' ### Notes > > **Note**: > > > As of PHP 8.0.0, the func\_\*() family of functions is intended to be mostly transparent with regard to named arguments, by treating the arguments as if they were all passed positionally, and missing arguments are replaced with their defaults. This function ignores the collection of unknown named variadic arguments. Unknown named arguments which are collected can only be accessed through the variadic parameter. > > > > > **Note**: > > > If the arguments are passed by reference, any changes to the arguments will be reflected in the values returned by this function. As of PHP 7 the current values will also be returned if the arguments are passed by value. > > > > **Note**: This function returns a copy of the passed arguments only, and does not account for default (non-passed) arguments. > > ### See Also * [`...` syntax](functions.arguments#functions.variable-arg-list) * [func\_get\_args()](function.func-get-args) * [func\_num\_args()](function.func-num-args) php Gmagick::rollimage Gmagick::rollimage ================== (PECL gmagick >= Unknown) Gmagick::rollimage — Offsets an image ### Description ``` public Gmagick::rollimage(int $x, int $y): Gmagick ``` Offsets an image as defined by x and y. ### Parameters `x` The x offset. `y` The y offset. ### Return Values The Gmagick object on success ### Errors/Exceptions Throws an **GmagickException** on error. php openssl_digest openssl\_digest =============== (PHP 5 >= 5.3.0, PHP 7, PHP 8) openssl\_digest — Computes a digest ### Description ``` openssl_digest(string $data, string $digest_algo, bool $binary = false): string|false ``` Computes a digest hash value for the given data using a given method, and returns a raw or binhex encoded string. ### Parameters `data` The data. `digest_algo` The digest method to use, e.g. "sha256", see [openssl\_get\_md\_methods()](function.openssl-get-md-methods) for a list of available digest methods. `binary` Setting to **`true`** will return as raw output data, otherwise the return value is binhex encoded. ### Return Values Returns the digested hash value on success or **`false`** on failure. ### Errors/Exceptions Emits an **`E_WARNING`** level error if an unknown signature algorithm is passed via the `digest_algo` parameter. ### See Also * [openssl\_get\_md\_methods()](function.openssl-get-md-methods) - Gets available digest methods php Event::addTimer Event::addTimer =============== (PECL event >= 1.2.6-beta) Event::addTimer — Alias of [Event::add()](event.add) ### Description This method is an alias of: [Event::add()](event.add) php PDOStatement::fetchColumn PDOStatement::fetchColumn ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.9.0) PDOStatement::fetchColumn — Returns a single column from the next row of a result set ### Description ``` public PDOStatement::fetchColumn(int $column = 0): mixed ``` Returns a single column from the next row of a result set or **`false`** if there are no more rows. > > **Note**: > > > **PDOStatement::fetchColumn()** should not be used to retrieve boolean columns, as it is impossible to distinguish a value of **`false`** from there being no more rows to retrieve. Use [PDOStatement::fetch()](pdostatement.fetch) instead. > > ### Parameters `column` 0-indexed number of the column you wish to retrieve from the row. If no value is supplied, **PDOStatement::fetchColumn()** fetches the first column. ### Return Values **PDOStatement::fetchColumn()** returns a single column from the next row of a result set or **`false`** if there are no more rows. **Warning** There is no way to return another column from the same row if you use **PDOStatement::fetchColumn()** to retrieve data. ### Examples **Example #1 Return first column of the next row** ``` <?php $sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); print("Fetch the first column from the first row in the result set:\n"); $result = $sth->fetchColumn(); print("name = $result\n"); print("Fetch the second column from the second row in the result set:\n"); $result = $sth->fetchColumn(1); print("colour = $result\n"); ?> ``` The above example will output: ``` Fetch the first column from the first row in the result set: name = lemon Fetch the second column from the second row in the result set: colour = red ``` ### See Also * [PDO::query()](pdo.query) - Prepares and executes an SQL statement without placeholders * [PDOStatement::fetch()](pdostatement.fetch) - Fetches the next row from a result set * [PDOStatement::fetchAll()](pdostatement.fetchall) - Fetches the remaining rows from a result set * [PDO::prepare()](pdo.prepare) - Prepares a statement for execution and returns a statement object * [PDOStatement::setFetchMode()](pdostatement.setfetchmode) - Set the default fetch mode for this statement php easter_date easter\_date ============ (PHP 4, PHP 5, PHP 7, PHP 8) easter\_date — Get Unix timestamp for midnight on Easter of a given year ### Description ``` easter_date(?int $year = null, int $mode = CAL_EASTER_DEFAULT): int ``` Returns the Unix timestamp corresponding to midnight on Easter of the given year. **Warning** This function will generate a warning if the year is outside of the range for Unix timestamps (i.e. typically before 1970 or after 2037 on 32bit systems). The date of Easter Day was defined by the Council of Nicaea in AD325 as the Sunday after the first full moon which falls on or after the Spring Equinox. The Equinox is assumed to always fall on 21st March, so the calculation reduces to determining the date of the full moon and the date of the following Sunday. The algorithm used here was introduced around the year 532 by Dionysius Exiguus. Under the Julian Calendar (for years before 1753) a simple 19-year cycle is used to track the phases of the Moon. Under the Gregorian Calendar (for years after 1753 - devised by Clavius and Lilius, and introduced by Pope Gregory XIII in October 1582, and into Britain and its then colonies in September 1752) two correction factors are added to make the cycle more accurate. ### Parameters `year` The year as a number between 1970 an 2037. If omitted or **`null`**, defaults to the current year according to the local time. `mode` Allows Easter dates to be calculated based on the Julian calendar when set to **`CAL_EASTER_ALWAYS_JULIAN`**. See also [calendar constants](https://www.php.net/manual/en/calendar.constants.php). ### Return Values The easter date as a unix timestamp. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `year` is nullable now. | ### Examples **Example #1 **easter\_date()** example** ``` <?php echo date("M-d-Y", easter_date(1999));        // Apr-04-1999 echo date("M-d-Y", easter_date(2000));        // Apr-23-2000 echo date("M-d-Y", easter_date(2001));        // Apr-15-2001 ?> ``` ### Notes > > **Note**: > > > **easter\_date()** relies on your system's C library time functions, rather than using PHP's internal date and time functions. As a consequence, **easter\_date()** uses the `TZ` environment variable to determine the time zone it should operate in, rather than using PHP's [default time zone](https://www.php.net/manual/en/datetime.configuration.php#ini.date.timezone), which may result in unexpected behaviour when using this function in conjunction with other date functions in PHP. > > As a workaround, you can use the [easter\_days()](function.easter-days) with [DateTime](class.datetime) and [DateInterval](class.dateinterval) to calculate the start of Easter in your PHP time zone as follows: > > > ``` > <?php > function get_easter_datetime($year) { >     $base = new DateTime("$year-03-21"); >     $days = easter_days($year); > >     return $base->add(new DateInterval("P{$days}D")); > } > > foreach (range(2012, 2015) as $year) { >     printf("Easter in %d is on %s\n", >            $year, >            get_easter_datetime($year)->format('F j')); > } > ?> > ``` > The above example will output: > > > ``` > > Easter in 2012 is on April 8 > Easter in 2013 is on March 31 > Easter in 2014 is on April 20 > Easter in 2015 is on April 5 > > ``` > ### See Also * [easter\_days()](function.easter-days) - Get number of days after March 21 on which Easter falls for a given year for calculating Easter before 1970 or after 2037
programming_docs
php The SolrInputDocument class The SolrInputDocument class =========================== Introduction ------------ (PECL solr >= 0.9.2) This class represents a Solr document that is about to be submitted to the Solr index. Class synopsis -------------- final class **SolrInputDocument** { /\* Constants \*/ const int [SORT\_DEFAULT](class.solrinputdocument#solrinputdocument.constants.sort-default) = 1; const int [SORT\_ASC](class.solrinputdocument#solrinputdocument.constants.sort-asc) = 1; const int [SORT\_DESC](class.solrinputdocument#solrinputdocument.constants.sort-desc) = 2; const int [SORT\_FIELD\_NAME](class.solrinputdocument#solrinputdocument.constants.sort-field-name) = 1; const int [SORT\_FIELD\_VALUE\_COUNT](class.solrinputdocument#solrinputdocument.constants.sort-field-value-count) = 2; const int [SORT\_FIELD\_BOOST\_VALUE](class.solrinputdocument#solrinputdocument.constants.sort-field-boost-value) = 4; /\* Methods \*/ public [\_\_construct](solrinputdocument.construct)() ``` public addChildDocument(SolrInputDocument $child): void ``` ``` public addChildDocuments(array &$docs): void ``` ``` public addField(string $fieldName, string $fieldValue, float $fieldBoostValue = 0.0): bool ``` ``` public clear(): bool ``` ``` public __clone(): void ``` ``` public deleteField(string $fieldName): bool ``` ``` public fieldExists(string $fieldName): bool ``` ``` public getBoost(): float ``` ``` public getChildDocuments(): array ``` ``` public getChildDocumentsCount(): int ``` ``` public getField(string $fieldName): SolrDocumentField ``` ``` public getFieldBoost(string $fieldName): float ``` ``` public getFieldCount(): int|false ``` ``` public getFieldNames(): array ``` ``` public hasChildDocuments(): bool ``` ``` public merge(SolrInputDocument $sourceDoc, bool $overwrite = true): bool ``` ``` public reset(): bool ``` ``` public setBoost(float $documentBoostValue): bool ``` ``` public setFieldBoost(string $fieldName, float $fieldBoostValue): bool ``` ``` public sort(int $sortOrderBy, int $sortDirection = SolrInputDocument::SORT_ASC): bool ``` ``` public toArray(): array ``` public [\_\_destruct](solrinputdocument.destruct)() } Predefined Constants -------------------- SolrInputDocument Class Constants --------------------------------- **`SolrInputDocument::SORT_DEFAULT`** Sorts the fields in ascending order. **`SolrInputDocument::SORT_ASC`** Sorts the fields in ascending order. **`SolrInputDocument::SORT_DESC`** Sorts the fields in descending order. **`SolrInputDocument::SORT_FIELD_NAME`** Sorts the fields by name **`SolrInputDocument::SORT_FIELD_VALUE_COUNT`** Sorts the fields by number of values. **`SolrInputDocument::SORT_FIELD_BOOST_VALUE`** Sorts the fields by boost value. Table of Contents ----------------- * [SolrInputDocument::addChildDocument](solrinputdocument.addchilddocument) — Adds a child document for block indexing * [SolrInputDocument::addChildDocuments](solrinputdocument.addchilddocuments) — Adds an array of child documents * [SolrInputDocument::addField](solrinputdocument.addfield) — Adds a field to the document * [SolrInputDocument::clear](solrinputdocument.clear) — Resets the input document * [SolrInputDocument::\_\_clone](solrinputdocument.clone) — Creates a copy of a SolrDocument * [SolrInputDocument::\_\_construct](solrinputdocument.construct) — Constructor * [SolrInputDocument::deleteField](solrinputdocument.deletefield) — Removes a field from the document * [SolrInputDocument::\_\_destruct](solrinputdocument.destruct) — Destructor * [SolrInputDocument::fieldExists](solrinputdocument.fieldexists) — Checks if a field exists * [SolrInputDocument::getBoost](solrinputdocument.getboost) — Retrieves the current boost value for the document * [SolrInputDocument::getChildDocuments](solrinputdocument.getchilddocuments) — Returns an array of child documents (SolrInputDocument) * [SolrInputDocument::getChildDocumentsCount](solrinputdocument.getchilddocumentscount) — Returns the number of child documents * [SolrInputDocument::getField](solrinputdocument.getfield) — Retrieves a field by name * [SolrInputDocument::getFieldBoost](solrinputdocument.getfieldboost) — Retrieves the boost value for a particular field * [SolrInputDocument::getFieldCount](solrinputdocument.getfieldcount) — Returns the number of fields in the document * [SolrInputDocument::getFieldNames](solrinputdocument.getfieldnames) — Returns an array containing all the fields in the document * [SolrInputDocument::hasChildDocuments](solrinputdocument.haschilddocuments) — Returns true if the document has any child documents * [SolrInputDocument::merge](solrinputdocument.merge) — Merges one input document into another * [SolrInputDocument::reset](solrinputdocument.reset) — Alias of SolrInputDocument::clear * [SolrInputDocument::setBoost](solrinputdocument.setboost) — Sets the boost value for this document * [SolrInputDocument::setFieldBoost](solrinputdocument.setfieldboost) — Sets the index-time boost value for a field * [SolrInputDocument::sort](solrinputdocument.sort) — Sorts the fields within the document * [SolrInputDocument::toArray](solrinputdocument.toarray) — Returns an array representation of the input document php SplFileObject::fgetc SplFileObject::fgetc ==================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::fgetc — Gets character from file ### Description ``` public SplFileObject::fgetc(): string|false ``` Gets a character from the file. ### Parameters This function has no parameters. ### Return Values Returns a string containing a single character read from the file or **`false`** on EOF. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Examples **Example #1 **SplFileObject::fgetc()** example** ``` <?php $file = new SplFileObject('file.txt'); while (false !== ($char = $file->fgetc())) {     echo "$char\n"; } ?> ``` ### See Also * [SplFileObject::fgets()](splfileobject.fgets) - Gets line from file php stats_dens_uniform stats\_dens\_uniform ==================== (PECL stats >= 1.0.0) stats\_dens\_uniform — Probability density function of the uniform distribution ### Description ``` stats_dens_uniform(float $x, float $a, float $b): float ``` Returns the probability density at `x`, where the random variable follows the uniform distribution of which the lower bound is `a` and the upper bound is `b`. ### Parameters `x` The value at which the probability density is calculated `a` The lower bound of the distribution `b` The upper bound of the distribution ### Return Values The probability density at `x` or **`false`** for failure. php Yaf_Dispatcher::getInstance Yaf\_Dispatcher::getInstance ============================ (Yaf >=1.0.0) Yaf\_Dispatcher::getInstance — Retrive the dispatcher instance ### Description ``` public static Yaf_Dispatcher::getInstance(): Yaf_Dispatcher ``` ### Parameters This function has no parameters. ### Return Values php Gmagick::getimagedepth Gmagick::getimagedepth ====================== (PECL gmagick >= Unknown) Gmagick::getimagedepth — Gets the depth of the image ### Description ``` public Gmagick::getimagedepth(): int ``` Gets the depth of the image. ### Parameters This function has no parameters. ### Return Values Image depth ### Errors/Exceptions Throws an **GmagickException** on error. php count count ===== (PHP 4, PHP 5, PHP 7, PHP 8) count — Counts all elements in an array or in a [Countable](class.countable) object ### Description ``` count(Countable|array $value, int $mode = COUNT_NORMAL): int ``` Counts all elements in an array when used with an array. When used with an object that implements the [Countable](class.countable) interface, it returns the return value of the method [Countable::count()](countable.count). ### Parameters `value` An array or [Countable](class.countable) object. `mode` If the optional `mode` parameter is set to **`COUNT_RECURSIVE`** (or 1), **count()** will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. **Caution** **count()** can detect recursion to avoid an infinite loop, but will emit an **`E_WARNING`** every time it does (in case the array contains itself more than once) and return a count higher than may be expected. ### Return Values Returns the number of elements in `value`. Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the [Countable](class.countable) interface, `1` would be returned, unless `value` was **`null`**, in which case `0` would be returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **count()** will now throw [TypeError](class.typeerror) on invalid countable types passed to the `value` parameter. | | 7.2.0 | **count()** will now yield a warning on invalid countable types passed to the `value` parameter. | ### Examples **Example #1 **count()** example** ``` <?php $a[0] = 1; $a[1] = 3; $a[2] = 5; var_dump(count($a)); $b[0]  = 7; $b[5]  = 9; $b[10] = 11; var_dump(count($b)); ?> ``` The above example will output: ``` int(3) int(3) ``` **Example #2 **count()** non Countable|array example (bad example - don't do this)** ``` <?php $b[0]  = 7; $b[5]  = 9; $b[10] = 11; var_dump(count($b)); var_dump(count(null)); var_dump(count(false)); ?> ``` The above example will output: ``` int(3) int(0) int(1) ``` Output of the above example in PHP 7.2: ``` int(3) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 int(0) Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 int(1) ``` Output of the above example in PHP 8: ``` int(3) Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12 ``` **Example #3 Recursive **count()** example** ``` <?php $food = array('fruits' => array('orange', 'banana', 'apple'),               'veggie' => array('carrot', 'collard', 'pea')); // recursive count var_dump(count($food, COUNT_RECURSIVE)); // normal count var_dump(count($food)); ?> ``` The above example will output: ``` int(8) int(2) ``` **Example #4 [Countable](class.countable) object** ``` <?php class CountOfMethods implements Countable {     private function someMethod()     {     }     public function count(): int     {         return count(get_class_methods($this));     } } $obj = new CountOfMethods(); var_dump(count($obj)); ?> ``` The above example will output: ``` int(2) ``` ### See Also * [is\_array()](function.is-array) - Finds whether a variable is an array * [isset()](function.isset) - Determine if a variable is declared and is different than null * [empty()](function.empty) - Determine whether a variable is empty * [strlen()](function.strlen) - Get string length * [is\_countable()](function.is-countable) - Verify that the contents of a variable is a countable value * [Arrays](language.types.array) php Imagick::getSize Imagick::getSize ================ (PECL imagick 2, PECL imagick 3) Imagick::getSize — Returns the size associated with the Imagick object ### Description ``` public Imagick::getSize(): array ``` Get the size in pixels associated with the Imagick object, previously set by [Imagick::setSize()](imagick.setsize). > > **Note**: > > > This method just returns the size that was set using [Imagick::setSize()](imagick.setsize). If you want to get the actual width / height of the image, use [Imagick::getImageWidth()](imagick.getimagewidth) and [Imagick::getImageHeight()](imagick.getimageheight). > > ### Parameters This function has no parameters. ### Return Values Returns the size associated with the Imagick object as an array with the keys "columns" and "rows". ### Examples **Example #1 Getting the size of a raw RGB image set at 200x400, after scaling to 400x800 (compared to width / height)** ``` <?php //Set size first and then load the raw image $img = new Imagick(); $img->setSize(200, 400); $img->readImage("image.rgb"); $img->scaleImage(400, 800); $size = $img->getSize(); print_r($size); echo $img->getImageWidth()."x".$img->getImageHeight(); ?> ``` The above example will output: ``` Array ( [columns] => 200 [rows] => 400 ) 400x800 ``` php Event::__construct Event::\_\_construct ==================== (PECL event >= 1.2.6-beta) Event::\_\_construct — Constructs Event object ### Description ``` public Event::__construct( EventBase $base , mixed $fd , int $what , callable $cb , mixed $arg = NULL ) ``` Constructs Event object. ### Parameters `base` The event base to associate with. `fd` stream resource, socket resource, or numeric file descriptor. For timer events pass **`-1`** . For signal events pass the signal number, e.g. **`SIGHUP`** . `what` Event flags. See [Event flags](https://www.php.net/manual/en/event.flags.php) . `cb` The event callback. See [Event callbacks](https://www.php.net/manual/en/event.callbacks.php) . `arg` Custom data. If specified, it will be passed to the callback when event triggers. ### Return Values Returns Event object. ### See Also * [Event::signal()](event.signal) - Constructs signal event object * [Event::timer()](event.timer) - Constructs timer event object php Imagick::previewImages Imagick::previewImages ====================== (PECL imagick 2, PECL imagick 3) Imagick::previewImages — Quickly pin-point appropriate parameters for image processing ### Description ``` public Imagick::previewImages(int $preview): bool ``` Tiles 9 thumbnails of the specified image with an image processing operation applied at varying strengths. This is helpful to quickly pin-point an appropriate parameter for an image processing operation. ### Parameters `preview` Preview type. See [Preview type constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.preview) ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php UConverter::getErrorMessage UConverter::getErrorMessage =========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::getErrorMessage — Get last error message on the object ### Description ``` public UConverter::getErrorMessage(): ?string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php getservbyport getservbyport ============= (PHP 4, PHP 5, PHP 7, PHP 8) getservbyport — Get Internet service which corresponds to port and protocol ### Description ``` getservbyport(int $port, string $protocol): string|false ``` **getservbyport()** returns the Internet service associated with `port` for the specified `protocol` as per /etc/services. ### Parameters `port` The port number. `protocol` `protocol` is either `"tcp"` or `"udp"` (in lowercase). ### Return Values Returns the Internet service name as a string, or **`false`** on failure. ### See Also * [getservbyname()](function.getservbyname) - Get port number associated with an Internet service and protocol php IntlTimeZone::createTimeZone IntlTimeZone::createTimeZone ============================ intltz\_create\_time\_zone ========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::createTimeZone -- intltz\_create\_time\_zone — Create a timezone object for the given ID ### Description Object-oriented style (method): ``` public static IntlTimeZone::createTimeZone(string $timezoneId): ?IntlTimeZone ``` Procedural style: ``` intltz_create_time_zone(string $timezoneId): ?IntlTimeZone ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `timezoneId` ### Return Values php SolrClient::__construct SolrClient::\_\_construct ========================= (PECL solr >= 0.9.2) SolrClient::\_\_construct — Constructor for the SolrClient object ### Description public **SolrClient::\_\_construct**(array `$clientOptions`) Constructor for the SolrClient object ### Parameters `clientOptions` This is an array containing one of the following keys : ``` - secure (Boolean value indicating whether or not to connect in secure mode) - hostname (The hostname for the Solr server) - port (The port number) - path (The path to solr) - wt (The name of the response writer e.g. xml, json) - login (The username used for HTTP Authentication, if any) - password (The HTTP Authentication password) - proxy_host (The hostname for the proxy server, if any) - proxy_port (The proxy port) - proxy_login (The proxy username) - proxy_password (The proxy password) - timeout (This is maximum time in seconds allowed for the http data transfer operation. Default is 30 seconds) - ssl_cert (File name to a PEM-formatted file containing the private key + private certificate (concatenated in that order) ) - ssl_key (File name to a PEM-formatted private key file only) - ssl_keypassword (Password for private key) - ssl_cainfo (Name of file holding one or more CA certificates to verify peer with) - ssl_capath (Name of directory holding multiple CA certificates to verify peer with ) Please note the if the ssl_cert file only contains the private certificate, you have to specify a separate ssl_key file The ssl_keypassword option is required if the ssl_cert or ssl_key options are set. ``` ### Errors/Exceptions Throws [SolrIllegalArgumentException](class.solrillegalargumentexception) on failure. ### Examples **Example #1 **SolrClient::\_\_construct()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT,     'path'     => SOLR_PATH_TO_SOLR,     'wt'       => 'xml', ); $client = new SolrClient($options); $doc = new SolrInputDocument(); $doc->addField('id', 334455); $doc->addField('cat', 'Software'); $doc->addField('cat', 'Lucene'); $updateResponse = $client->addDocument($doc); ?> ``` The above example will output something similar to: ### See Also * [SolrClient::getOptions()](solrclient.getoptions) - Returns the client options set internally php ImagickDraw::rectangle ImagickDraw::rectangle ====================== (PECL imagick 2, PECL imagick 3) ImagickDraw::rectangle — Draws a rectangle ### Description ``` public ImagickDraw::rectangle( float $x1, float $y1, float $x2, float $y2 ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a rectangle given two coordinates and using the current stroke, stroke width, and fill settings. ### Parameters `x1` x coordinate of the top left corner `y1` y coordinate of the top left corner `x2` x coordinate of the bottom right corner `y2` y coordinate of the bottom right corner ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::rectangle()** example** ``` <?php function rectangle($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $strokeColor = new \ImagickPixel($strokeColor);     $fillColor = new \ImagickPixel($fillColor);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeOpacity(1);     $draw->setStrokeWidth(2);     $draw->rectangle(200, 200, 300, 300);     $imagick = new \Imagick();     $imagick->newImage(500, 500, $backgroundColor);     $imagick->setImageFormat("png");     $imagick->drawImage($draw);     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ```
programming_docs
php var_export var\_export =========== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) var\_export — Outputs or returns a parsable string representation of a variable ### Description ``` var_export(mixed $value, bool $return = false): ?string ``` **var\_export()** gets structured information about the given variable. It is similar to [var\_dump()](function.var-dump) with one exception: the returned representation is valid PHP code. ### Parameters `value` The variable you want to export. `return` If used and set to **`true`**, **var\_export()** will return the variable representation instead of outputting it. ### Return Values Returns the variable representation when the `return` parameter is used and evaluates to **`true`**. Otherwise, this function will return **`null`**. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | Now exports [stdClass](class.stdclass) objects as an array cast to an object (`(object) array( ... )`), rather than using the nonexistent method **stdClass::\_\_setState()**. The practical effect is that now [stdClass](class.stdclass) is exportable, and the resulting code will even work on earlier versions of PHP. | ### Examples **Example #1 **var\_export()** Examples** ``` <?php $a = array (1, 2, array ("a", "b", "c")); var_export($a); ?> ``` The above example will output: ``` array ( 0 => 1, 1 => 2, 2 => array ( 0 => 'a', 1 => 'b', 2 => 'c', ), ) ``` ``` <?php $b = 3.1; $v = var_export($b, true); echo $v; ?> ``` The above example will output: ``` 3.1 ``` **Example #2 Exporting stdClass (since PHP 7.3.0)** ``` <?php $person = new stdClass; $person->name = 'ElePHPant ElePHPantsdotter'; $person->website = 'https://php.net/elephpant.php'; var_export($person); ``` The above example will output: ``` (object) array( 'name' => 'ElePHPant ElePHPantsdotter', 'website' => 'https://php.net/elephpant.php', ) ``` **Example #3 Exporting classes** ``` <?php class A { public $var; } $a = new A; $a->var = 5; var_export($a); ?> ``` The above example will output: ``` A::__set_state(array( 'var' => 5, )) ``` **Example #4 Using [\_\_set\_state()](language.oop5.magic#object.set-state)** ``` <?php class A {     public $var1;     public $var2;     public static function __set_state($an_array)     {         $obj = new A;         $obj->var1 = $an_array['var1'];         $obj->var2 = $an_array['var2'];         return $obj;     } } $a = new A; $a->var1 = 5; $a->var2 = 'foo'; eval('$b = ' . var_export($a, true) . ';'); // $b = A::__set_state(array(                                             //    'var1' => 5,                                             //    'var2' => 'foo',                                             // )); var_dump($b); ?> ``` The above example will output: ``` object(A)#2 (2) { ["var1"]=> int(5) ["var2"]=> string(3) "foo" } ``` ### Notes > > **Note**: > > > Variables of type resource couldn't be exported by this function. > > > > **Note**: > > > **var\_export()** does not handle circular references as it would be close to impossible to generate parsable PHP code for that. If you want to do something with the full representation of an array or object, use [serialize()](function.serialize). > > **Warning** When **var\_export()** exports objects, the leading backslash is not included in the class name of namespaced classes for maximum compatibility. > > **Note**: > > > To be able to evaluate the PHP generated by **var\_export()**, all processed objects must implement the magic [\_\_set\_state](language.oop5.magic#object.set-state) method. The only exception is [stdClass](class.stdclass), which is exported using an array cast to an object. > > ### See Also * [print\_r()](function.print-r) - Prints human-readable information about a variable * [serialize()](function.serialize) - Generates a storable representation of a value * [var\_dump()](function.var-dump) - Dumps information about a variable php imap_rfc822_write_address imap\_rfc822\_write\_address ============================ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_rfc822\_write\_address — Returns a properly formatted email address given the mailbox, host, and personal info ### Description ``` imap_rfc822_write_address(string $mailbox, string $hostname, string $personal): string|false ``` Returns a properly formatted email address as defined in [» RFC2822](http://www.faqs.org/rfcs/rfc2822) given the needed information. ### Parameters `mailbox` The mailbox name, see [imap\_open()](function.imap-open) for more information **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `hostname` The email host part `personal` The name of the account owner ### Return Values Returns a string properly formatted email address as defined in [» RFC2822](http://www.faqs.org/rfcs/rfc2822), or **`false`** on failure. ### Examples **Example #1 **imap\_rfc822\_write\_address()** example** ``` <?php echo imap_rfc822_write_address("hartmut", "example.com", "Hartmut Holzgraefe"); ?> ``` The above example will output: ``` Hartmut Holzgraefe <[email protected]> ``` php CachingIterator::key CachingIterator::key ==================== (PHP 5, PHP 7, PHP 8) CachingIterator::key — Return the key for the current element ### Description ``` public CachingIterator::key(): scalar ``` **Warning**This function is currently not documented; only its argument list is available. This method may return a key for the current element. ### Parameters This function has no parameters. php IntlCalendar::after IntlCalendar::after =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::after — Whether this objectʼs time is after that of the passed object ### Description Object-oriented style ``` public IntlCalendar::after(IntlCalendar $other): bool ``` Procedural style ``` intlcal_after(IntlCalendar $calendar, IntlCalendar $other): bool ``` Returns whether this objectʼs time succeeds the argumentʼs time. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `other` The calendar whose time will be checked against the primary objectʼs time. ### Return Values Returns **`true`** if this objectʼs current time is after that of the `calendar` argumentʼs time. Returns **`false`** otherwise. On failure **`false`** is also returned. To detect error conditions use [intl\_get\_error\_code()](function.intl-get-error-code), or set up Intl to throw [exceptions](https://www.php.net/manual/en/intl.configuration.php#ini.intl.use-exceptions). ### Examples **Example #1 **IntlCalendar::after()**** ``` <?php $cal1 = IntlCalendar::createInstance(); $cal2 = clone $cal1; var_dump($cal1->after($cal2), //false         $cal2->after($cal1)); //false $cal1->roll(IntlCalendar::FIELD_MILLISECOND, true); var_dump($cal1->after($cal2), //true         $cal2->after($cal1)); //false ``` php Imagick::getImageHeight Imagick::getImageHeight ======================= (PECL imagick 2, PECL imagick 3) Imagick::getImageHeight — Returns the image height ### Description ``` public Imagick::getImageHeight(): int ``` Returns the image height. ### Parameters This function has no parameters. ### Return Values Returns the image height in pixels. ### Errors/Exceptions Throws ImagickException on error. php tidy::getRelease tidy::getRelease ================ tidy\_get\_release ================== (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy::getRelease -- tidy\_get\_release — Get release date (version) for Tidy library ### Description Object-oriented style ``` public tidy::getRelease(): string ``` Procedural style ``` tidy_get_release(): string ``` Gets the release date of the Tidy library. ### Parameters This function has no parameters. ### Return Values Returns a string with the release date of the Tidy library, which may be `'unknown'`. php imap_num_msg imap\_num\_msg ============== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_num\_msg — Gets the number of messages in the current mailbox ### Description ``` imap_num_msg(IMAP\Connection $imap): int|false ``` Gets the number of messages in the current mailbox. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. ### Return Values Return the number of messages in the current mailbox, as an integer, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_num\_recent()](function.imap-num-recent) - Gets the number of recent messages in current mailbox * [imap\_status()](function.imap-status) - Returns status information on a mailbox php XMLWriter::startPi XMLWriter::startPi ================== xmlwriter\_start\_pi ==================== (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::startPi -- xmlwriter\_start\_pi — Create start PI tag ### Description Object-oriented style ``` public XMLWriter::startPi(string $target): bool ``` Procedural style ``` xmlwriter_start_pi(XMLWriter $writer, string $target): bool ``` Starts a processing instruction tag. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `target` The target of the processing instruction. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::endPi()](xmlwriter.endpi) - End current PI * [XMLWriter::writePi()](xmlwriter.writepi) - Writes a PI php dba_insert dba\_insert =========== (PHP 4, PHP 5, PHP 7, PHP 8) dba\_insert — Insert entry ### Description ``` dba_insert(string|array $key, string $value, resource $dba): bool ``` **dba\_insert()** inserts the entry described with `key` and `value` into the database. ### Parameters `key` The key of the entry to be inserted. If this key already exist in the database, this function will fail. Use [dba\_replace()](function.dba-replace) if you need to replace an existent key. `value` The value to be inserted. `dba` The database handler, returned by [dba\_open()](function.dba-open) or [dba\_popen()](function.dba-popen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [dba\_exists()](function.dba-exists) - Check whether key exists * [dba\_delete()](function.dba-delete) - Delete DBA entry specified by key * [dba\_fetch()](function.dba-fetch) - Fetch data specified by key * [dba\_replace()](function.dba-replace) - Replace or insert entry php array_rand array\_rand =========== (PHP 4, PHP 5, PHP 7, PHP 8) array\_rand — Pick one or more random keys out of an array ### Description ``` array_rand(array $array, int $num = 1): int|string|array ``` Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. **Caution** This function does not generate cryptographically secure values, and *must not* be used for cryptographic purposes, or purposes that require returned values to be unguessable. If cryptographically secure randomness is required, the [Random\Randomizer](https://www.php.net/manual/en/class.random-randomizer.php) may be used with the [Random\Engine\Secure](https://www.php.net/manual/en/class.random-engine-secure.php) engine. For simple use cases, the [random\_int()](https://www.php.net/manual/en/function.random-int.php) and [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php) functions provide a convenient and secure API that is backed by the operating system’s CSPRNG. ### Parameters `array` The input array. `num` Specifies how many entries should be picked. ### Return Values When picking only one entry, **array\_rand()** returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. If multiple keys are returned, they will be returned in the order they were present in the original array. Trying to pick more elements than there are in the array will result in an **`E_WARNING`** level error, and NULL will be returned. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | The internal randomization algorithm [has been changed](https://www.php.net/manual/en/migration71.incompatible.php#migration71.incompatible.rand-srand-aliases) to use the [» Mersenne Twister](http://www.math.sci.hiroshima-u.ac.jp/~m-mat/MT/emt.html) Random Number Generator instead of the libc rand function. | ### Examples **Example #1 **array\_rand()** example** ``` <?php $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); $rand_keys = array_rand($input, 2); echo $input[$rand_keys[0]] . "\n"; echo $input[$rand_keys[1]] . "\n"; ?> ``` ### See Also * [Random\Randomizer::pickArrayKeys()](https://www.php.net/manual/en/random-randomizer.pickarraykeys.php) - Select random array keys * [Random\Randomizer::shuffleArray()](https://www.php.net/manual/en/random-randomizer.shufflearray.php) - Get a permutation of an array php Parle\Parser::push Parle\Parser::push ================== (PECL parle >= 0.5.1) Parle\Parser::push — Add a grammar rule ### Description ``` public Parle\Parser::push(string $name, string $rule): int ``` Push a grammar rule. The production id returned can be used later in the parsing process to identify the rule matched. ### Parameters `name` Rule name. `rule` The rule to be added. The syntax is Bison compatible. ### Return Values Returns int representing the rule index. php XMLReader::moveToElement XMLReader::moveToElement ======================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::moveToElement — Position cursor on the parent Element of current Attribute ### Description ``` public XMLReader::moveToElement(): bool ``` Moves cursor to the parent Element of current Attribute. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if successful and **`false`** if it fails or not positioned on Attribute when this method is called. ### See Also * [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute * [XMLReader::moveToAttributeNo()](xmlreader.movetoattributeno) - Move cursor to an attribute by index * [XMLReader::moveToAttributeNs()](xmlreader.movetoattributens) - Move cursor to a named attribute * [XMLReader::moveToFirstAttribute()](xmlreader.movetofirstattribute) - Position cursor on the first Attribute php The GmagickDraw class The GmagickDraw class ===================== Introduction ------------ (PECL gmagick >= Unknown) Class synopsis -------------- class **GmagickDraw** { /\* Methods \*/ ``` public annotate(float $x, float $y, string $text): GmagickDraw ``` ``` public arc( float $sx, float $sy, float $ex, float $ey, float $sd, float $ed ): GmagickDraw ``` ``` public bezier(array $coordinate_array): GmagickDraw ``` ``` public ellipse( float $ox, float $oy, float $rx, float $ry, float $start, float $end ): GmagickDraw ``` ``` public getfillcolor(): GmagickPixel ``` ``` public getfillopacity(): float ``` ``` public getfont(): mixed ``` ``` public getfontsize(): float ``` ``` public getfontstyle(): int ``` ``` public getfontweight(): int ``` ``` public getstrokecolor(): GmagickPixel ``` ``` public getstrokeopacity(): float ``` ``` public getstrokewidth(): float ``` ``` public gettextdecoration(): int ``` ``` public gettextencoding(): mixed ``` ``` public line( float $sx, float $sy, float $ex, float $ey ): GmagickDraw ``` ``` public point(float $x, float $y): GmagickDraw ``` ``` public polygon(array $coordinates): GmagickDraw ``` ``` public polyline(array $coordinate_array): GmagickDraw ``` ``` public rectangle( float $x1, float $y1, float $x2, float $y2 ): GmagickDraw ``` ``` public rotate(float $degrees): GmagickDraw ``` ``` public roundrectangle( float $x1, float $y1, float $x2, float $y2, float $rx, float $ry ): GmagickDraw ``` ``` public scale(float $x, float $y): GmagickDraw ``` ``` public setfillcolor(mixed $color): GmagickDraw ``` ``` public setfillopacity(float $fill_opacity): GmagickDraw ``` ``` public setfont(string $font): GmagickDraw ``` ``` public setfontsize(float $pointsize): GmagickDraw ``` ``` public setfontstyle(int $style): GmagickDraw ``` ``` public setfontweight(int $weight): GmagickDraw ``` ``` public setstrokecolor(mixed $color): GmagickDraw ``` ``` public setstrokeopacity(float $stroke_opacity): GmagickDraw ``` ``` public setstrokewidth(float $width): GmagickDraw ``` ``` public settextdecoration(int $decoration): GmagickDraw ``` ``` public settextencoding(string $encoding): GmagickDraw ``` } Table of Contents ----------------- * [GmagickDraw::annotate](gmagickdraw.annotate) — Draws text on the image * [GmagickDraw::arc](gmagickdraw.arc) — Draws an arc * [GmagickDraw::bezier](gmagickdraw.bezier) — Draws a bezier curve * [GmagickDraw::ellipse](gmagickdraw.ellipse) — Draws an ellipse on the image * [GmagickDraw::getfillcolor](gmagickdraw.getfillcolor) — Returns the fill color * [GmagickDraw::getfillopacity](gmagickdraw.getfillopacity) — Returns the opacity used when drawing * [GmagickDraw::getfont](gmagickdraw.getfont) — Returns the font * [GmagickDraw::getfontsize](gmagickdraw.getfontsize) — Returns the font pointsize * [GmagickDraw::getfontstyle](gmagickdraw.getfontstyle) — Returns the font style * [GmagickDraw::getfontweight](gmagickdraw.getfontweight) — Returns the font weight * [GmagickDraw::getstrokecolor](gmagickdraw.getstrokecolor) — Returns the color used for stroking object outlines * [GmagickDraw::getstrokeopacity](gmagickdraw.getstrokeopacity) — Returns the opacity of stroked object outlines * [GmagickDraw::getstrokewidth](gmagickdraw.getstrokewidth) — Returns the width of the stroke used to draw object outlines * [GmagickDraw::gettextdecoration](gmagickdraw.gettextdecoration) — Returns the text decoration * [GmagickDraw::gettextencoding](gmagickdraw.gettextencoding) — Returns the code set used for text annotations * [GmagickDraw::line](gmagickdraw.line) — Draws a line * [GmagickDraw::point](gmagickdraw.point) — Draws a point * [GmagickDraw::polygon](gmagickdraw.polygon) — Draws a polygon * [GmagickDraw::polyline](gmagickdraw.polyline) — Draws a polyline * [GmagickDraw::rectangle](gmagickdraw.rectangle) — Draws a rectangle * [GmagickDraw::rotate](gmagickdraw.rotate) — Applies the specified rotation to the current coordinate space * [GmagickDraw::roundrectangle](gmagickdraw.roundrectangle) — Draws a rounded rectangle * [GmagickDraw::scale](gmagickdraw.scale) — Adjusts the scaling factor * [GmagickDraw::setfillcolor](gmagickdraw.setfillcolor) — Sets the fill color to be used for drawing filled objects * [GmagickDraw::setfillopacity](gmagickdraw.setfillopacity) — The setfillopacity purpose * [GmagickDraw::setfont](gmagickdraw.setfont) — Sets the fully-specified font to use when annotating with text * [GmagickDraw::setfontsize](gmagickdraw.setfontsize) — Sets the font pointsize to use when annotating with text * [GmagickDraw::setfontstyle](gmagickdraw.setfontstyle) — Sets the font style to use when annotating with text * [GmagickDraw::setfontweight](gmagickdraw.setfontweight) — Sets the font weight * [GmagickDraw::setstrokecolor](gmagickdraw.setstrokecolor) — Sets the color used for stroking object outlines * [GmagickDraw::setstrokeopacity](gmagickdraw.setstrokeopacity) — Specifies the opacity of stroked object outlines * [GmagickDraw::setstrokewidth](gmagickdraw.setstrokewidth) — Sets the width of the stroke used to draw object outlines * [GmagickDraw::settextdecoration](gmagickdraw.settextdecoration) — Specifies a decoration * [GmagickDraw::settextencoding](gmagickdraw.settextencoding) — Specifies the text code set
programming_docs
php pcntl_async_signals pcntl\_async\_signals ===================== (PHP 7 >= 7.1.0, PHP 8) pcntl\_async\_signals — Enable/disable asynchronous signal handling or return the old setting ### Description ``` pcntl_async_signals(?bool $enable = null): bool ``` If the `enable` parameter is **`null`**, **pcntl\_async\_signals()** returns whether asynchronous signal handling is enabled. Otherwise, asynchronous signal handling is enabled or disabled. ### Parameters `enable` Whether asynchronous signal handling should be enabled. ### Return Values When used as getter (`enable` parameter is **`null`**) it returns whether asynchronous signal handling is enabled. When used as setter (`enable` parameter is not **`null`**), it returns whether asynchronous signal handling was enabled *before* the function call. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `enable` is nullable now. | ### See Also * [declare](control-structures.declare) php Yaf_Request_Http::getFiles Yaf\_Request\_Http::getFiles ============================ (Yaf >=1.0.0) Yaf\_Request\_Http::getFiles — The getFiles purpose ### Description ``` public Yaf_Request_Http::getFiles(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php pg_ping pg\_ping ======== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_ping — Ping database connection ### Description ``` pg_ping(?PgSql\Connection $connection = null): bool ``` **pg\_ping()** pings a database connection and tries to reconnect it if it is broken. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is **`null`**, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `connection` is now nullable. | ### Examples **Example #1 **pg\_ping()** example** ``` <?php  $conn = pg_pconnect("dbname=publisher"); if (!$conn) {   echo "An error occurred.\n";   exit; } if (!pg_ping($conn))   die("Connection is broken\n"); ?> ``` ### See Also * [pg\_connection\_status()](function.pg-connection-status) - Get connection status * [pg\_connection\_reset()](function.pg-connection-reset) - Reset connection (reconnect) php Ds\Map::sort Ds\Map::sort ============ (PECL ds >= 1.0.0) Ds\Map::sort — Sorts the map in-place by value ### Description ``` public Ds\Map::sort(callable $comparator = ?): void ``` Sorts the map in-place by value, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Map::sort()** example** ``` <?php $map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]); $map->sort(); print_r($map); ?> ``` The above example will output something similar to: ``` Ds\Map Object ( [0] => Ds\Pair Object ( [key] => c [value] => 1 ) [1] => Ds\Pair Object ( [key] => a [value] => 2 ) [2] => Ds\Pair Object ( [key] => b [value] => 3 ) ) ``` **Example #2 **Ds\Map::sort()** example using a comparator** ``` <?php $map = new \Ds\Map(["a" => 2, "b" => 3, "c" => 1]); $map->sort(function($a, $b) {     return $b <=> $a; }); print_r($map); ?> ``` The above example will output something similar to: ``` Ds\Map Object ( [0] => Ds\Pair Object ( [key] => b [value] => 3 ) [1] => Ds\Pair Object ( [key] => a [value] => 2 ) [2] => Ds\Pair Object ( [key] => c [value] => 1 ) ) ``` php XMLReader::getAttributeNs XMLReader::getAttributeNs ========================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::getAttributeNs — Get the value of an attribute by localname and URI ### Description ``` public XMLReader::getAttributeNs(string $name, string $namespace): ?string ``` Returns the value of an attribute by name and namespace URI or an empty string if attribute does not exist or not positioned on an element node. ### Parameters `name` The local name. `namespace` The namespace URI. ### Return Values The value of the attribute, or **`null`** if no attribute with the given `name` and `namespace` is found or not positioned of element. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function can no longer return **`false`**. | ### See Also * [XMLReader::getAttribute()](xmlreader.getattribute) - Get the value of a named attribute * [XMLReader::getAttributeNo()](xmlreader.getattributeno) - Get the value of an attribute by index php bzclose bzclose ======= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) bzclose — Close a bzip2 file ### Description ``` bzclose(resource $bz): bool ``` Closes the given bzip2 file pointer. ### Parameters `bz` The file pointer. It must be valid and must point to a file successfully opened by [bzopen()](function.bzopen). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [bzopen()](function.bzopen) - Opens a bzip2 compressed file php snmp2_getnext snmp2\_getnext ============== (PHP >= 5.2.0, PHP 7, PHP 8) snmp2\_getnext — Fetch the SNMP object which follows the given object id ### Description ``` snmp2_getnext( string $hostname, string $community, array|string $object_id, int $timeout = -1, int $retries = -1 ): mixed ``` The **snmp2\_get\_next()** function is used to read the value of the SNMP object that follows the specified `object_id`. ### Parameters `hostname` The hostname of the SNMP agent (server). `community` The read community. `object_id` The SNMP object id which precedes the wanted one. `timeout` The number of microseconds until the first timeout. `retries` The number of times to retry if timeouts occur. ### Return Values Returns SNMP object value on success or **`false`** on error. In case of an error, an E\_WARNING message is shown. ### Examples **Example #1 Using **snmp2\_get\_next()**** ``` <?php $nameOfSecondInterface = snmp2_get_next('localhost', 'public', 'IF-MIB::ifName.1'); ?> ``` ### See Also * [snmp2\_get()](function.snmp2-get) - Fetch an SNMP object * [snmp2\_walk()](function.snmp2-walk) - Fetch all the SNMP objects from an agent php SolrQuery::setTermsPrefix SolrQuery::setTermsPrefix ========================= (PECL solr >= 0.9.2) SolrQuery::setTermsPrefix — Restrict matches to terms that start with the prefix ### Description ``` public SolrQuery::setTermsPrefix(string $prefix): SolrQuery ``` Restrict matches to terms that start with the prefix ### Parameters `prefix` Restrict matches to terms that start with the prefix ### Return Values Returns the current SolrQuery object, if the return value is used. php The DOMDocumentType class The DOMDocumentType class ========================= Introduction ------------ (PHP 5, PHP 7, PHP 8) Each [DOMDocument](class.domdocument) has a `doctype` attribute whose value is either **`null`** or a **DOMDocumentType** object. Class synopsis -------------- class **DOMDocumentType** extends [DOMNode](class.domnode) { /\* Properties \*/ public readonly string [$name](class.domdocumenttype#domdocumenttype.props.name); public readonly [DOMNamedNodeMap](class.domnamednodemap) [$entities](class.domdocumenttype#domdocumenttype.props.entities); public readonly [DOMNamedNodeMap](class.domnamednodemap) [$notations](class.domdocumenttype#domdocumenttype.props.notations); public readonly string [$publicId](class.domdocumenttype#domdocumenttype.props.publicid); public readonly string [$systemId](class.domdocumenttype#domdocumenttype.props.systemid); public readonly ?string [$internalSubset](class.domdocumenttype#domdocumenttype.props.internalsubset); /\* Inherited properties \*/ public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Inherited methods \*/ ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Properties ---------- publicId The public identifier of the external subset. systemId The system identifier of the external subset. This may be an absolute URI or not. name The name of DTD; i.e., the name immediately following the `DOCTYPE` keyword. entities A [DOMNamedNodeMap](class.domnamednodemap) containing the general entities, both external and internal, declared in the DTD. notations A [DOMNamedNodeMap](class.domnamednodemap) containing the notations declared in the DTD. internalSubset The internal subset as a string, or **`null`** if there is none. This does not contain the delimiting square brackets. php ImagickDraw::getGravity ImagickDraw::getGravity ======================= (PECL imagick 2, PECL imagick 3) ImagickDraw::getGravity — Returns the text placement gravity ### Description ``` public ImagickDraw::getGravity(): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the text placement gravity used when annotating with text. ### Return Values Returns a [GRAVITY](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.gravity) constant (`imagick::GRAVITY_*`) on success and 0 if no gravity is set. php ReflectionClass::getModifiers ReflectionClass::getModifiers ============================= (PHP 5, PHP 7, PHP 8) ReflectionClass::getModifiers — Gets the class modifiers ### Description ``` public ReflectionClass::getModifiers(): int ``` Returns a bitfield of the access modifiers for this class. ### Parameters This function has no parameters. ### Return Values Returns bitmask of [modifier constants](class.reflectionclass#reflectionclass.constants.modifiers). ### See Also * [ReflectionClass::getProperties()](reflectionclass.getproperties) - Gets properties * [Reflection::getModifierNames()](reflection.getmodifiernames) - Gets modifier names php DOMImplementation::__construct DOMImplementation::\_\_construct ================================ (PHP 5, PHP 7) DOMImplementation::\_\_construct — Creates a new DOMImplementation object ### Description **DOMImplementation::\_\_construct**() Creates a new [DOMImplementation](class.domimplementation) object. ### Parameters This function has no parameters. php EventBuffer::unlock EventBuffer::unlock =================== (PECL event >= 1.2.6-beta) EventBuffer::unlock — Releases lock acquired by EventBuffer::lock ### Description ``` public EventBuffer::unlock(): bool ``` Releases lock acquired by [EventBuffer::lock()](eventbuffer.lock) . ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBuffer::lock()](eventbuffer.lock) - Acquires a lock on buffer php None Enumerations ------------ ### Basic Enumerations Enumerations are a restricting layer on top of classes and class constants, intended to provide a way to define a closed set of possible values for a type. ``` <?php enum Suit {     case Hearts;     case Diamonds;     case Clubs;     case Spades; } function do_stuff(Suit $s) {     // ... } do_stuff(Suit::Spades); ?> ``` For a full discussion, see the [Enumerations](https://www.php.net/manual/en/language.enumerations.php) chapter. ### Casting If an enum is converted to an object, it is not modified. If an enum is converted to an array, an array with a single `name` key (for Pure enums) or an array with both `name` and `value` keys (for Backed enums) is created. All other cast types will result in an error. php eio_futime eio\_futime =========== (PECL eio >= 0.0.1dev) eio\_futime — Change file last access and modification times ### Description ``` eio_futime( mixed $fd, float $atime, float $mtime, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_futime()** changes file last access and modification times. ### Parameters `fd` Stream, Socket resource, or numeric file descriptor, e.g. returned by [eio\_open()](function.eio-open) `atime` Access time `mtime` Modification time `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_futime()** returns request resource on success, or **`false`** on failure. ### See Also * [eio\_utime()](function.eio-utime) - Change file last access and modification times php Yaf_Dispatcher::setView Yaf\_Dispatcher::setView ======================== (Yaf >=1.0.0) Yaf\_Dispatcher::setView — Set a custom view engine ### Description ``` public Yaf_Dispatcher::setView(Yaf_View_Interface $view): Yaf_Dispatcher ``` This method provides a solution if you want use a custom view engine instead of [Yaf\_View\_Simple](class.yaf-view-simple) ### Parameters `view` A [Yaf\_View\_Interface](class.yaf-view-interface) instance ### Return Values ### Examples **Example #1 **A custom View engine()** example** ``` <?php require "/path/to/smarty/Smarty.class.php"; class Smarty_Adapter implements Yaf_View_Interface {     /**      * Smarty object      * @var Smarty      */     public $_smarty;       /**      * Constructor      *      * @param string $tmplPath      * @param array $extraParams      * @return void      */     public function __construct($tmplPath = null, $extraParams = array()) {         $this->_smarty = new Smarty;           if (null !== $tmplPath) {             $this->setScriptPath($tmplPath);         }           foreach ($extraParams as $key => $value) {             $this->_smarty->$key = $value;         }     }       /**      * Set the path to the templates      *      * @param string $path The directory to set as the path.      * @return void      */     public function setScriptPath($path)     {         if (is_readable($path)) {             $this->_smarty->template_dir = $path;             return;         }           throw new Exception('Invalid path provided');     }       /**      * Assign a variable to the template      *      * @param string $key The variable name.      * @param mixed $val The variable value.      * @return void      */     public function __set($key, $val)     {         $this->_smarty->assign($key, $val);     }       /**      * Allows testing with empty() and isset() to work      *      * @param string $key      * @return boolean      */     public function __isset($key)     {         return (null !== $this->_smarty->get_template_vars($key));     }       /**      * Allows unset() on object properties to work      *      * @param string $key      * @return void      */     public function __unset($key)     {         $this->_smarty->clear_assign($key);     }       /**      * Assign variables to the template      *      * Allows setting a specific key to the specified value, OR passing      * an array of key => value pairs to set en masse.      *      * @see __set()      * @param string|array $spec The assignment strategy to use (key or      * array of key => value pairs)      * @param mixed $value (Optional) If assigning a named variable,      * use this as the value.      * @return void      */     public function assign($spec, $value = null) {         if (is_array($spec)) {             $this->_smarty->assign($spec);             return;         }           $this->_smarty->assign($spec, $value);     }       /**      * Clear all assigned variables      *      * Clears all variables assigned to Yaf_View either via      * {@link assign()} or property overloading      * ({@link __get()}/{@link __set()}).      *      * @return void      */     public function clearVars() {         $this->_smarty->clear_all_assign();     }       /**      * Processes a template and returns the output.      *      * @param string $name The template to process.      * @return string The output.      */     public function render($name, $value = NULL) {         return $this->_smarty->fetch($name);     }     public function display($name, $value = NULL) {         echo $this->_smarty->fetch($name);     } } ?> ``` **Example #2 **Yaf\_Dispatcher::setView()** example** ``` <?php class Bootstrap extends Yaf_Bootstrap_Abstract {     /**      * there are some config for smarty in the config:      *      * smarty.left_delimiter   = "{{"      * smarty.right_delimiter  = "}}"      * smarty.template_dir     = APPLICATION_PATH "/views/scripts/"      * smarty.compile_dir      = APPLICATION_PATH "/views/templates_c/"      * smarty.cache_dir        = APPLICATION_PATH "/views/templates_d/"      *      */     public function _initConfig() {         $config = Yaf_Application::app()->getConfig();         Yaf_Registry::set("config", $config);     }     public function _initLocalName() {         /** we put class Smarty_Adapter under the local library directory */         Yaf_Loader::getInstance()->registerLocalNamespace('Smarty');     }     public function _initSmarty(Yaf_Dispatcher $dispatcher) {         $smarty = new Smarty_Adapter(null, Yaf_Registry::get("config")->get("smarty"));         $dispatcher->setView($smarty);         /* now the Smarty view engine become the default view engine of Yaf */     } } ?> ``` ### See Also * [Yaf\_View\_Interface](class.yaf-view-interface) * [Yaf\_View\_Simple](class.yaf-view-simple)
programming_docs
php ReflectionFunction::isDisabled ReflectionFunction::isDisabled ============================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunction::isDisabled — Checks if function is disabled **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public ReflectionFunction::isDisabled(): bool ``` Checks if the function is disabled, via the [disable\_functions](https://www.php.net/manual/en/ini.core.php#ini.disable-functions) directive. ### Parameters This function has no parameters. ### Return Values **`true`** if it's disable, otherwise **`false`** ### See Also * [ReflectionFunctionAbstract::isUserDefined()](reflectionfunctionabstract.isuserdefined) - Checks if user defined * [disable\_functions directive](https://www.php.net/manual/en/ini.core.php#ini.disable-functions) php ArrayAccess::offsetGet ArrayAccess::offsetGet ====================== (PHP 5, PHP 7, PHP 8) ArrayAccess::offsetGet — Offset to retrieve ### Description ``` public ArrayAccess::offsetGet(mixed $offset): mixed ``` Returns the value at specified offset. This method is executed when checking if offset is [empty()](function.empty). ### Parameters `offset` The offset to retrieve. ### Return Values Can return all value types. ### Notes > > **Note**: > > > It's possible for implementations of this method to return by reference. This makes indirect modifications to the overloaded array dimensions of [ArrayAccess](class.arrayaccess) objects possible. > > A direct modification is one that replaces completely the value of the array dimension, as in `$obj[6] = 7`. An indirect modification, on the other hand, only changes part of the dimension, or attempts to assign the dimension by reference to another variable, as in `$obj[6][7] = 7` or `$var =& $obj[6]`. Increments with `++` and decrements with `--` are also implemented in a way that requires indirect modification. > > While direct modification triggers a call to [ArrayAccess::offsetSet()](arrayaccess.offsetset), indirect modification triggers a call to **ArrayAccess::offsetGet()**. In that case, the implementation of **ArrayAccess::offsetGet()** must be able to return by reference, otherwise an **`E_NOTICE`** message is raised. > > ### See Also * [ArrayAccess::offsetExists()](arrayaccess.offsetexists) - Whether an offset exists php restore_error_handler restore\_error\_handler ======================= (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) restore\_error\_handler — Restores the previous error handler function ### Description ``` restore_error_handler(): bool ``` Used after changing the error handler function using [set\_error\_handler()](function.set-error-handler), to revert to the previous error handler (which could be the built-in or a user defined function). ### Parameters This function has no parameters. ### Return Values This function always returns **`true`**. ### Examples **Example #1 **restore\_error\_handler()** example** Decide if [unserialize()](function.unserialize) caused an error, then restore the original error handler. ``` <?php function unserialize_handler($errno, $errstr) {     echo "Invalid serialized value.\n"; } $serialized = 'foo'; set_error_handler('unserialize_handler'); $original = unserialize($serialized); restore_error_handler(); ?> ``` The above example will output: ``` Invalid serialized value. ``` ### See Also * [error\_reporting()](function.error-reporting) - Sets which PHP errors are reported * [set\_error\_handler()](function.set-error-handler) - Sets a user-defined error handler function * [restore\_exception\_handler()](function.restore-exception-handler) - Restores the previously defined exception handler function * [trigger\_error()](function.trigger-error) - Generates a user-level error/warning/notice message php mailparse_msg_get_structure mailparse\_msg\_get\_structure ============================== (PECL mailparse >= 0.9.0) mailparse\_msg\_get\_structure — Returns an array of mime section names in the supplied message ### Description ``` mailparse_msg_get_structure(resource $mimemail): array ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `mimemail` A valid `MIME` resource. php gmmktime gmmktime ======== (PHP 4, PHP 5, PHP 7, PHP 8) gmmktime — Get Unix timestamp for a GMT date ### Description ``` gmmktime( int $hour, ?int $minute = null, ?int $second = null, ?int $month = null, ?int $day = null, ?int $year = null ): int|false ``` Identical to [mktime()](function.mktime) except the passed parameters represents a GMT date. **gmmktime()** internally uses [mktime()](function.mktime) so only times valid in derived local time can be used. Like [mktime()](function.mktime), arguments may be left out in order from right to left, with any omitted arguments being set to the current corresponding GMT value. Calling **gmmktime()** without arguments is deprecated. [time()](function.time) can be used to get the current timestamp. ### Parameters `hour` The number of the hour relative to the start of the day determined by `month`, `day` and `year`. Negative values reference the hour before midnight of the day in question. Values greater than 23 reference the appropriate hour in the following day(s). `minute` The number of the minute relative to the start of the `hour`. Negative values reference the minute in the previous hour. Values greater than 59 reference the appropriate minute in the following hour(s). `second` The number of seconds relative to the start of the `minute`. Negative values reference the second in the previous minute. Values greater than 59 reference the appropriate second in the following minute(s). `month` The number of the month relative to the end of the previous year. Values 1 to 12 reference the normal calendar months of the year in question. Values less than 1 (including negative values) reference the months in the previous year in reverse order, so 0 is December, -1 is November, etc. Values greater than 12 reference the appropriate month in the following year(s). `day` The number of the day relative to the end of the previous month. Values 1 to 28, 29, 30 or 31 (depending upon the month) reference the normal days in the relevant month. Values less than 1 (including negative values) reference the days in the previous month, so 0 is the last day of the previous month, -1 is the day before that, etc. Values greater than the number of days in the relevant month reference the appropriate day in the following month(s). `year` The year ### Return Values Returns a int Unix timestamp on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `hour` is no longer optional. | | 8.0.0 | `minute`, `second`, `month`, `day` and `year` are nullable now. | ### Examples **Example #1 **gmmktime()** basic example** ``` <?php // Prints: July 1, 2000 is on a Saturday echo "July 1, 2000 is on a " . date("l", gmmktime(0, 0, 0, 7, 1, 2000)); ?> ``` ### See Also * The [DateTimeImmutable](class.datetimeimmutable) class * [mktime()](function.mktime) - Get Unix timestamp for a date * [date()](function.date) - Format a Unix timestamp * [time()](function.time) - Return current Unix timestamp php imagecreatetruecolor imagecreatetruecolor ==================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagecreatetruecolor — Create a new true color image ### Description ``` imagecreatetruecolor(int $width, int $height): GdImage|false ``` **imagecreatetruecolor()** returns an image object representing a black image of the specified size. ### Parameters `width` Image width. `height` Image height. ### Return Values Returns an image object on success, **`false`** on errors. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [GDImage](class.gdimage) instance now; previously, a resource was returned. | ### Examples **Example #1 Creating a new GD image stream and outputting an image.** ``` <?php header ('Content-Type: image/png'); $im = @imagecreatetruecolor(120, 20)       or die('Cannot Initialize new GD image stream'); $text_color = imagecolorallocate($im, 233, 14, 91); imagestring($im, 1, 5, 5,  'A Simple Text String', $text_color); imagepng($im); imagedestroy($im); ?> ``` The above example will output something similar to: ### See Also * [imagedestroy()](function.imagedestroy) - Destroy an image * [imagecreate()](function.imagecreate) - Create a new palette based image php Gmagick::getimagecolorspace Gmagick::getimagecolorspace =========================== (PECL gmagick >= Unknown) Gmagick::getimagecolorspace — Gets the image colorspace ### Description ``` public Gmagick::getimagecolorspace(): int ``` Gets the image colorspace. ### Parameters This function has no parameters. ### Return Values Colorspace ### Errors/Exceptions Throws an **GmagickException** on error. php Yac::dump Yac::dump ========= (PECL yac >= 1.0.0) Yac::dump — Dump cache ### Description ``` public Yac::dump(int $$num): mixed ``` Dump values stored in cache ### Parameters `num` Maximum number of items should be returned ### Return Values mixed php Memcached::getAllKeys Memcached::getAllKeys ===================== (PECL memcached >= 2.0.0) Memcached::getAllKeys — Gets the keys stored on all the servers ### Description ``` public Memcached::getAllKeys(): array|false ``` **Memcached::getAllKeys()** queries each memcache server and retrieves an array of all keys stored on them at that point in time. This is not an atomic operation, so it isn't a truly consistent snapshot of the keys at point in time. As memcache doesn't guarantee to return all keys you also cannot assume that all keys have been returned. ### Parameters This function has no parameters. ### Return Values Returns the keys stored on all the servers on success or **`false`** on failure. php ReflectionClassConstant::__construct ReflectionClassConstant::\_\_construct ====================================== (PHP 7 >= 7.1.0, PHP 8) ReflectionClassConstant::\_\_construct — Constructs a ReflectionClassConstant ### Description public **ReflectionClassConstant::\_\_construct**(object|string `$class`, string `$constant`) Constructs a new [ReflectionClassConstant](class.reflectionclassconstant) object. ### Parameters `class` Either a string containing the name of the class to reflect, or an object. `constant` The name of the class constant. ### Errors/Exceptions Throws an [Exception](class.exception) in case the given class constant does not exist. ### See Also * [Constructors](language.oop5.decon#language.oop5.decon.constructor) php trait_exists trait\_exists ============= (PHP 5 >= 5.4.0, PHP 7, PHP 8) trait\_exists — Checks if the trait exists ### Description ``` trait_exists(string $trait, bool $autoload = true): bool ``` ### Parameters `trait` Name of the trait to check `autoload` Whether to autoload if not already loaded. ### Return Values Returns **`true`** if trait exists, and **`false`** otherwise. php Yaf_View_Simple::__isset Yaf\_View\_Simple::\_\_isset ============================ (Yaf >=1.0.0) Yaf\_View\_Simple::\_\_isset — The \_\_isset purpose ### Description ``` public Yaf_View_Simple::__isset(string $name): void ``` ### Parameters `name` ### Return Values php EventHttpRequest::findHeader EventHttpRequest::findHeader ============================ (PECL event >= 1.4.0-beta) EventHttpRequest::findHeader — Finds the value belonging a header ### Description ``` public EventHttpRequest::findHeader( string $key , string $type ): void ``` Finds the value belonging a header. ### Parameters `key` The header name. `type` One of [`EventHttpRequest::*_HEADER` constants](class.eventhttprequest#eventhttprequest.constants) . ### Return Values Returns **`null`** if header not found. ### See Also * [EventHttpRequest::addHeader()](eventhttprequest.addheader) - Adds an HTTP header to the headers of the request php php_sapi_name php\_sapi\_name =============== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) php\_sapi\_name — Returns the type of interface between web server and PHP ### Description ``` php_sapi_name(): string|false ``` Returns a lowercase string that describes the type of interface (the Server API, SAPI) that PHP is using. For example, in CLI PHP this string will be "cli" whereas with Apache it may have several different values depending on the exact SAPI used. Possible values are listed below. ### Parameters This function has no parameters. ### Return Values Returns the interface type, as a lowercase string, or **`false`** on failure. Although not exhaustive, the possible return values include `apache`, `apache2handler`, `cgi` (until PHP 5.3), `cgi-fcgi`, `cli`, `cli-server`, `embed`, `fpm-fcgi`, `litespeed`, `phpdbg`. ### Examples **Example #1 **php\_sapi\_name()** example** This example checks for the substring `cgi` because it may also be `cgi-fcgi`. ``` <?php $sapi_type = php_sapi_name(); if (substr($sapi_type, 0, 3) == 'cgi') {     echo "You are using CGI PHP\n"; } else {     echo "You are not using CGI PHP\n"; } ?> ``` ### Notes > > **Note**: **An alternative approach** > > > > The PHP constant **`PHP_SAPI`** has the same value as **php\_sapi\_name()**. > > **Tip** A potential gotcha ================== The defined SAPI may not be obvious, because for example instead of `apache` it may be defined as `apache2handler`. ### See Also * [PHP\_SAPI](https://www.php.net/manual/en/reserved.constants.php#reserved.constants.core) php Yaf_Request_Simple::getCookie Yaf\_Request\_Simple::getCookie =============================== (Yaf >=1.0.0) Yaf\_Request\_Simple::getCookie — The getCookie purpose ### Description ``` public Yaf_Request_Simple::getCookie(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php time_nanosleep time\_nanosleep =============== (PHP 5, PHP 7, PHP 8) time\_nanosleep — Delay for a number of seconds and nanoseconds ### Description ``` time_nanosleep(int $seconds, int $nanoseconds): array|bool ``` Delays program execution for the given number of `seconds` and `nanoseconds`. ### Parameters `seconds` Must be a non-negative integer. `nanoseconds` Must be a non-negative integer less than 1 billion. > **Note**: On Windows, the system may sleep longer that the given number of nanoseconds, depending on the hardware. > > ### Return Values Returns **`true`** on success or **`false`** on failure. If the delay was interrupted by a signal, an associative array will be returned with the components: * `seconds` - number of seconds remaining in the delay * `nanoseconds` - number of nanoseconds remaining in the delay ### Examples **Example #1 **time\_nanosleep()** example** ``` <?php // Careful! This won't work as expected if an array is returned if (time_nanosleep(0, 500000000)) {     echo "Slept for half a second.\n"; } // This is better: if (time_nanosleep(0, 500000000) === true) {     echo "Slept for half a second.\n"; } // And this is the best: $nano = time_nanosleep(2, 100000); if ($nano === true) {     echo "Slept for 2 seconds, 100 microseconds.\n"; } elseif ($nano === false) {     echo "Sleeping failed.\n"; } elseif (is_array($nano)) {     $seconds = $nano['seconds'];     $nanoseconds = $nano['nanoseconds'];     echo "Interrupted by a signal.\n";     echo "Time remaining: $seconds seconds, $nanoseconds nanoseconds."; } ?> ``` ### See Also * [sleep()](function.sleep) - Delay execution * [usleep()](function.usleep) - Delay execution in microseconds * [time\_sleep\_until()](function.time-sleep-until) - Make the script sleep until the specified time * [set\_time\_limit()](function.set-time-limit) - Limits the maximum execution time php EventHttpConnection::setMaxBodySize EventHttpConnection::setMaxBodySize =================================== (PECL event >= 1.2.6-beta) EventHttpConnection::setMaxBodySize — Sets maximum body size for the connection ### Description ``` public EventHttpConnection::setMaxBodySize( string $max_size ): void ``` Sets maximum body size for the connection. ### Parameters `max_size` The maximum body size in bytes. ### Return Values No value is returned. ### See Also * [EventHttpConnection::setMaxHeadersSize()](eventhttpconnection.setmaxheaderssize) - Sets maximum header size php ImagickPixelIterator::clear ImagickPixelIterator::clear =========================== (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::clear — Clear resources associated with a PixelIterator ### Description ``` public ImagickPixelIterator::clear(): bool ``` **Warning**This function is currently not documented; only its argument list is available. Clear resources associated with a PixelIterator. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **ImagickPixelIterator::clear()**** ``` <?php function clear($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $imageIterator = $imagick->getPixelRegionIterator(100, 100, 250, 200);     /* Loop through pixel rows */     foreach ($imageIterator as $pixels) {          /** @var $pixel \ImagickPixel */         /* Loop through the pixels in the row (columns) */         foreach ($pixels as $column => $pixel) {              if ($column % 2) {                 /* Paint every second pixel black*/                 $pixel->setColor("rgba(0, 0, 0, 0)");              }         }         /* Sync the iterator, this is important to do on each iteration */         $imageIterator->syncIterator();     }     $imageIterator->clear();     header("Content-Type: image/jpg");     echo $imagick; } ?> ``` php pg_result_seek pg\_result\_seek ================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_result\_seek — Set internal row offset in result instance ### Description ``` pg_result_seek(PgSql\Result $result, int $row): bool ``` **pg\_result\_seek()** sets the internal row offset in the `result` instance. ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `row` Row to move the internal offset to in the [PgSql\Result](class.pgsql-result) instance. Rows are numbered starting from zero. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_result\_seek()** example** ``` <?php // Connect to the database $conn = pg_pconnect("dbname=publisher"); // Execute a query $result = pg_query($conn, "SELECT author, email FROM authors"); // Seek to the 3rd row (assuming there are 3 rows) pg_result_seek($result, 2); // Fetch the 3rd row $row = pg_fetch_row($result);   ?> ``` ### See Also * [pg\_fetch\_row()](function.pg-fetch-row) - Get a row as an enumerated array * [pg\_fetch\_assoc()](function.pg-fetch-assoc) - Fetch a row as an associative array * [pg\_fetch\_array()](function.pg-fetch-array) - Fetch a row as an array * [pg\_fetch\_object()](function.pg-fetch-object) - Fetch a row as an object * [pg\_fetch\_result()](function.pg-fetch-result) - Returns values from a result instance
programming_docs
php PDO::setAttribute PDO::setAttribute ================= (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.1.0) PDO::setAttribute — Set an attribute ### Description ``` public PDO::setAttribute(int $attribute, mixed $value): bool ``` Sets an attribute on the database handle. Some available generic attributes are listed below; some drivers may make use of additional driver specific attributes. Note that driver specific attributes *must not* be used with other drivers. **`PDO::ATTR_CASE`** Force column names to a specific case. Can take one of the following values: **`PDO::CASE_LOWER`** Force column names to lower case. **`PDO::CASE_NATURAL`** Leave column names as returned by the database driver. **`PDO::CASE_UPPER`** Force column names to upper case. **`PDO::ATTR_ERRMODE`** Error reporting mode of PDO. Can take one of the following values: **`PDO::ERRMODE_SILENT`** Only sets error codes. **`PDO::ERRMODE_WARNING`** Raises **`E_WARNING`** diagnostics. **`PDO::ERRMODE_EXCEPTION`** Throws [PDOException](class.pdoexception)s. **`PDO::ATTR_ORACLE_NULLS`** > **Note**: This attribute is available with all drivers, not just Oracle. > > Determines if and how **`null`** and empty strings should be converted. Can take one of the following values: **`PDO::NULL_NATURAL`** No conversion takes place. **`PDO::NULL_EMPTY_STRING`** Empty strings get converted to **`null`**. **`PDO::NULL_TO_STRING`** **`null`** gets converted to an empty string. **`PDO::ATTR_STRINGIFY_FETCHES`** Whether to convert numeric values to strings when fetching. Takes a value of type bool: **`true`** to enable and **`false`** to disable. **`PDO::ATTR_STATEMENT_CLASS`** Set user-supplied statement class derived from PDOStatement. Requires `array(string classname, array(mixed constructor_args))`. **Caution** Cannot be used with persistent PDO instances. **`PDO::ATTR_TIMEOUT`** Specifies the timeout duration in seconds. Takes a value of type int. > > **Note**: > > > Not all drivers support this option, and its meaning may differ from driver to driver. For example, SQLite will wait for up to this time value before giving up on obtaining a writable lock, but other drivers may interpret this as a connection or a read timeout interval. > > **`PDO::ATTR_AUTOCOMMIT`** > **Note**: Only available for the OCI, Firebird, and MySQL drivers. > > Whether to autocommit every single statement. Takes a value of type bool: **`true`** to enable and **`false`** to disable. By default, **`true`**. **`PDO::ATTR_EMULATE_PREPARES`** > **Note**: Only available for the OCI, Firebird, and MySQL drivers. > > Whether enable or disable emulation of prepared statements. Some drivers do not support prepared statements natively or have limited support for them. If set to **`true`** PDO will always emulate prepared statements, otherwise PDO will attempt to use native prepared statements. In case the driver cannot successfully prepare the current query, PDO will always fall back to emulating the prepared statement. **`PDO::MYSQL_ATTR_USE_BUFFERED_QUERY`** > **Note**: Only available for the MySQL driver. > > Whether to use buffered queries. Takes a value of type bool: **`true`** to enable and **`false`** to disable. By default, **`false`**. **`PDO::ATTR_DEFAULT_FETCH_MODE`** Set the default fetch mode. A description of the modes and how to use them is available in the [PDOStatement::fetch()](pdostatement.fetch) documentation. ### Parameters `attribute` The attribute to modify. `value` The value to set the `attribute`, might require a specific type depending on the attribute. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [PDO::getAttribute()](pdo.getattribute) - Retrieve a database connection attribute * [PDOStatement::getAttribute()](pdostatement.getattribute) - Retrieve a statement attribute * [PDOStatement::setAttribute()](pdostatement.setattribute) - Set a statement attribute php openssl_pkey_get_details openssl\_pkey\_get\_details =========================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) openssl\_pkey\_get\_details — Returns an array with the key details ### Description ``` openssl_pkey_get_details(OpenSSLAsymmetricKey $key): array|false ``` This function returns the key details (bits, key, type). ### Parameters `key` Resource holding the key. ### Return Values Returns an array with the key details in success or **`false`** in failure. Returned array has indexes `bits` (number of bits), `key` (string representation of the public key) and `type` (type of the key which is one of **`OPENSSL_KEYTYPE_RSA`**, **`OPENSSL_KEYTYPE_DSA`**, **`OPENSSL_KEYTYPE_DH`**, **`OPENSSL_KEYTYPE_EC`** or -1 meaning unknown). Depending on the key type used, additional details may be returned. Note that some elements may not always be available. * **`OPENSSL_KEYTYPE_RSA`**, an additional array key named `"rsa"`, containing the key data is returned. | Key | Description | | --- | --- | | `"n"` | modulus | | `"e"` | public exponent | | `"d"` | private exponent | | `"p"` | prime 1 | | `"q"` | prime 2 | | `"dmp1"` | exponent1, d mod (p-1) | | `"dmq1"` | exponent2, d mod (q-1) | | `"iqmp"` | coefficient, (inverse of q) mod p | * **`OPENSSL_KEYTYPE_DSA`**, an additional array key named `"dsa"`, containing the key data is returned. | Key | Description | | --- | --- | | `"p"` | prime number (public) | | `"q"` | 160-bit subprime, q | p-1 (public) | | `"g"` | generator of subgroup (public) | | `"priv_key"` | private key x | | `"pub_key"` | public key y = g^x | * **`OPENSSL_KEYTYPE_DH`**, an additional array key named `"dh"`, containing the key data is returned. | Key | Description | | --- | --- | | `"p"` | prime number (shared) | | `"g"` | generator of Z\_p (shared) | | `"priv_key"` | private DH value x | | `"pub_key"` | public DH value g^x | * **`OPENSSL_KEYTYPE_EC`**, an additional array key named `"ec"`, containing the key data is returned. | Key | Description | | --- | --- | | `"curve_name"` | name of curve, see [openssl\_get\_curve\_names()](function.openssl-get-curve-names) | | `"curve_oid"` | ASN1 Object identifier (OID) for EC curve. | | `"x"` | x coordinate (public) | | `"y"` | y coordinate (public) | | `"d"` | private key | ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) now; previously, a [resource](language.types.resource) of type `OpenSSL key` was accepted. | php PharFileInfo::__destruct PharFileInfo::\_\_destruct ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) PharFileInfo::\_\_destruct — Destructs a Phar entry object ### Description public **PharFileInfo::\_\_destruct**() ### Parameters This function has no parameters. php The ZookeeperOperationTimeoutException class The ZookeeperOperationTimeoutException class ============================================ Introduction ------------ (PECL zookeeper >= 0.3.0) The ZooKeeper operation timeout exception handling class. Class synopsis -------------- class **ZookeeperOperationTimeoutException** extends [ZookeeperException](class.zookeeperexception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php is_array is\_array ========= (PHP 4, PHP 5, PHP 7, PHP 8) is\_array — Finds whether a variable is an array ### Description ``` is_array(mixed $value): bool ``` Finds whether the given variable is an array. ### Parameters `value` The variable being evaluated. ### Return Values Returns **`true`** if `value` is an array, **`false`** otherwise. ### Examples **Example #1 Check that variable is an array** ``` <?php $yes = array('this', 'is', 'an array'); echo is_array($yes) ? 'Array' : 'not an Array'; echo "\n"; $no = 'this is a string'; echo is_array($no) ? 'Array' : 'not an Array'; ?> ``` The above example will output: ``` Array not an Array ``` ### See Also * [array\_is\_list()](function.array-is-list) - Checks whether a given array is a list * [is\_float()](function.is-float) - Finds whether the type of a variable is float * [is\_int()](function.is-int) - Find whether the type of a variable is integer * [is\_string()](function.is-string) - Find whether the type of a variable is string * [is\_object()](function.is-object) - Finds whether a variable is an object php ImagickDraw::pathLineToVerticalAbsolute ImagickDraw::pathLineToVerticalAbsolute ======================================= (PECL imagick 2, PECL imagick 3) ImagickDraw::pathLineToVerticalAbsolute — Draws a vertical line ### Description ``` public ImagickDraw::pathLineToVerticalAbsolute(float $y): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws a vertical line path from the current point to the target point using absolute coordinates. The target point then becomes the new current point. ### Parameters `y` y coordinate ### Return Values No value is returned. php NoRewindIterator::__construct NoRewindIterator::\_\_construct =============================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) NoRewindIterator::\_\_construct — Construct a NoRewindIterator ### Description public **NoRewindIterator::\_\_construct**([Iterator](class.iterator) `$iterator`) Constructs a NoRewindIterator. ### Parameters `iterator` The iterator being used. ### Examples **Example #1 **NoRewindIterator::\_\_construct()** example** The second loop does not output because the iterator is only used once, as it does not rewind. ``` <?php $fruit = array('apple', 'banana', 'cranberry'); $arr = new ArrayObject($fruit); $it  = new NoRewindIterator($arr->getIterator()); echo "Fruit A:\n"; foreach( $it as $item ) {     echo $item . "\n"; } echo "Fruit B:\n"; foreach( $it as $item ) {     echo $item . "\n"; } ?> ``` The above example will output something similar to: ``` Fruit A: apple banana cranberry Fruit B: ``` ### See Also * [NoRewindIterator::valid()](norewinditerator.valid) - Validates the iterator php fdf_add_template fdf\_add\_template ================== (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_add\_template — Adds a template into the FDF document ### Description ``` fdf_add_template( resource $fdf_document, int $newpage, string $filename, string $template, int $rename ): bool ``` **Warning**This function is currently not documented; only its argument list is available. php Ds\Collection::copy Ds\Collection::copy =================== (PECL ds >= 1.0.0) Ds\Collection::copy — Returns a shallow copy of the collection ### Description ``` abstract public Ds\Collection::copy(): Ds\Collection ``` Returns a shallow copy of the collection. ### Parameters This function has no parameters. ### Return Values Returns a shallow copy of the collection. ### Examples **Example #1 **Ds\Collection::copy()** example** ``` <?php $a = new \Ds\Vector([1, 2, 3]); $b = $a->copy(); $b->push(4); print_r($a); print_r($b); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 ) ``` php The ReflectionClass class The ReflectionClass class ========================= Introduction ------------ (PHP 5, PHP 7, PHP 8) The **ReflectionClass** class reports information about a class. Class synopsis -------------- class **ReflectionClass** implements [Reflector](class.reflector) { /\* Constants \*/ public const int [IS\_IMPLICIT\_ABSTRACT](class.reflectionclass#reflectionclass.constants.is-implicit-abstract); public const int [IS\_EXPLICIT\_ABSTRACT](class.reflectionclass#reflectionclass.constants.is-explicit-abstract); public const int [IS\_FINAL](class.reflectionclass#reflectionclass.constants.is-final); public const int [IS\_READONLY](class.reflectionclass#reflectionclass.constants.is-readonly); /\* Properties \*/ public string [$name](class.reflectionclass#reflectionclass.props.name); /\* Methods \*/ public [\_\_construct](reflectionclass.construct)(object|string `$objectOrClass`) ``` public static export(mixed $argument, bool $return = false): string ``` ``` public getAttributes(?string $name = null, int $flags = 0): array ``` ``` public getConstant(string $name): mixed ``` ``` public getConstants(?int $filter = null): array ``` ``` public getConstructor(): ?ReflectionMethod ``` ``` public getDefaultProperties(): array ``` ``` public getDocComment(): string|false ``` ``` public getEndLine(): int|false ``` ``` public getExtension(): ?ReflectionExtension ``` ``` public getExtensionName(): string|false ``` ``` public getFileName(): string|false ``` ``` public getInterfaceNames(): array ``` ``` public getInterfaces(): array ``` ``` public getMethod(string $name): ReflectionMethod ``` ``` public getMethods(?int $filter = null): array ``` ``` public getModifiers(): int ``` ``` public getName(): string ``` ``` public getNamespaceName(): string ``` ``` public getParentClass(): ReflectionClass|false ``` ``` public getProperties(?int $filter = null): array ``` ``` public getProperty(string $name): ReflectionProperty ``` ``` public getReflectionConstant(string $name): ReflectionClassConstant|false ``` ``` public getReflectionConstants(?int $filter = null): array ``` ``` public getShortName(): string ``` ``` public getStartLine(): int|false ``` ``` public getStaticProperties(): ?array ``` ``` public getStaticPropertyValue(string $name, mixed &$def_value = ?): mixed ``` ``` public getTraitAliases(): array ``` ``` public getTraitNames(): array ``` ``` public getTraits(): array ``` ``` public hasConstant(string $name): bool ``` ``` public hasMethod(string $name): bool ``` ``` public hasProperty(string $name): bool ``` ``` public implementsInterface(ReflectionClass|string $interface): bool ``` ``` public inNamespace(): bool ``` ``` public isAbstract(): bool ``` ``` public isAnonymous(): bool ``` ``` public isCloneable(): bool ``` ``` public isEnum(): bool ``` ``` public isFinal(): bool ``` ``` public isInstance(object $object): bool ``` ``` public isInstantiable(): bool ``` ``` public isInterface(): bool ``` ``` public isInternal(): bool ``` ``` public isIterable(): bool ``` ``` public isReadOnly(): bool ``` ``` public isSubclassOf(ReflectionClass|string $class): bool ``` ``` public isTrait(): bool ``` ``` public isUserDefined(): bool ``` ``` public newInstance(mixed ...$args): object ``` ``` public newInstanceArgs(array $args = []): ?object ``` ``` public newInstanceWithoutConstructor(): object ``` ``` public setStaticPropertyValue(string $name, mixed $value): void ``` ``` public __toString(): string ``` } Properties ---------- name Name of the class. Read-only, throws [ReflectionException](class.reflectionexception) in attempt to write. Predefined Constants -------------------- ReflectionClass Modifiers ------------------------- **`ReflectionClass::IS_IMPLICIT_ABSTRACT`** Indicates the class is [abstract](language.oop5.abstract) because it has some abstract methods. **`ReflectionClass::IS_EXPLICIT_ABSTRACT`** Indicates the class is [abstract](language.oop5.abstract) because of its definition. **`ReflectionClass::IS_FINAL`** Indicates the class is [final](language.oop5.final). **`ReflectionClass::IS_READONLY`** Indicates the class is [readonly](language.oop5.basic#language.oop5.basic.class.readonly). Table of Contents ----------------- * [ReflectionClass::\_\_construct](reflectionclass.construct) — Constructs a ReflectionClass * [ReflectionClass::export](reflectionclass.export) — Exports a class * [ReflectionClass::getAttributes](reflectionclass.getattributes) — Gets Attributes * [ReflectionClass::getConstant](reflectionclass.getconstant) — Gets defined constant * [ReflectionClass::getConstants](reflectionclass.getconstants) — Gets constants * [ReflectionClass::getConstructor](reflectionclass.getconstructor) — Gets the constructor of the class * [ReflectionClass::getDefaultProperties](reflectionclass.getdefaultproperties) — Gets default properties * [ReflectionClass::getDocComment](reflectionclass.getdoccomment) — Gets doc comments * [ReflectionClass::getEndLine](reflectionclass.getendline) — Gets end line * [ReflectionClass::getExtension](reflectionclass.getextension) — Gets a ReflectionExtension object for the extension which defined the class * [ReflectionClass::getExtensionName](reflectionclass.getextensionname) — Gets the name of the extension which defined the class * [ReflectionClass::getFileName](reflectionclass.getfilename) — Gets the filename of the file in which the class has been defined * [ReflectionClass::getInterfaceNames](reflectionclass.getinterfacenames) — Gets the interface names * [ReflectionClass::getInterfaces](reflectionclass.getinterfaces) — Gets the interfaces * [ReflectionClass::getMethod](reflectionclass.getmethod) — Gets a ReflectionMethod for a class method * [ReflectionClass::getMethods](reflectionclass.getmethods) — Gets an array of methods * [ReflectionClass::getModifiers](reflectionclass.getmodifiers) — Gets the class modifiers * [ReflectionClass::getName](reflectionclass.getname) — Gets class name * [ReflectionClass::getNamespaceName](reflectionclass.getnamespacename) — Gets namespace name * [ReflectionClass::getParentClass](reflectionclass.getparentclass) — Gets parent class * [ReflectionClass::getProperties](reflectionclass.getproperties) — Gets properties * [ReflectionClass::getProperty](reflectionclass.getproperty) — Gets a ReflectionProperty for a class's property * [ReflectionClass::getReflectionConstant](reflectionclass.getreflectionconstant) — Gets a ReflectionClassConstant for a class's constant * [ReflectionClass::getReflectionConstants](reflectionclass.getreflectionconstants) — Gets class constants * [ReflectionClass::getShortName](reflectionclass.getshortname) — Gets short name * [ReflectionClass::getStartLine](reflectionclass.getstartline) — Gets starting line number * [ReflectionClass::getStaticProperties](reflectionclass.getstaticproperties) — Gets static properties * [ReflectionClass::getStaticPropertyValue](reflectionclass.getstaticpropertyvalue) — Gets static property value * [ReflectionClass::getTraitAliases](reflectionclass.gettraitaliases) — Returns an array of trait aliases * [ReflectionClass::getTraitNames](reflectionclass.gettraitnames) — Returns an array of names of traits used by this class * [ReflectionClass::getTraits](reflectionclass.gettraits) — Returns an array of traits used by this class * [ReflectionClass::hasConstant](reflectionclass.hasconstant) — Checks if constant is defined * [ReflectionClass::hasMethod](reflectionclass.hasmethod) — Checks if method is defined * [ReflectionClass::hasProperty](reflectionclass.hasproperty) — Checks if property is defined * [ReflectionClass::implementsInterface](reflectionclass.implementsinterface) — Implements interface * [ReflectionClass::inNamespace](reflectionclass.innamespace) — Checks if in namespace * [ReflectionClass::isAbstract](reflectionclass.isabstract) — Checks if class is abstract * [ReflectionClass::isAnonymous](reflectionclass.isanonymous) — Checks if class is anonymous * [ReflectionClass::isCloneable](reflectionclass.iscloneable) — Returns whether this class is cloneable * [ReflectionClass::isEnum](reflectionclass.isenum) — Returns whether this is an enum * [ReflectionClass::isFinal](reflectionclass.isfinal) — Checks if class is final * [ReflectionClass::isInstance](reflectionclass.isinstance) — Checks class for instance * [ReflectionClass::isInstantiable](reflectionclass.isinstantiable) — Checks if the class is instantiable * [ReflectionClass::isInterface](reflectionclass.isinterface) — Checks if the class is an interface * [ReflectionClass::isInternal](reflectionclass.isinternal) — Checks if class is defined internally by an extension, or the core * [ReflectionClass::isIterable](reflectionclass.isiterable) — Check whether this class is iterable * [ReflectionClass::isIterateable](reflectionclass.isiterateable) — Alias of ReflectionClass::isIterable * [ReflectionClass::isReadOnly](reflectionclass.isreadonly) — Checks if class is readonly * [ReflectionClass::isSubclassOf](reflectionclass.issubclassof) — Checks if a subclass * [ReflectionClass::isTrait](reflectionclass.istrait) — Returns whether this is a trait * [ReflectionClass::isUserDefined](reflectionclass.isuserdefined) — Checks if user defined * [ReflectionClass::newInstance](reflectionclass.newinstance) — Creates a new class instance from given arguments * [ReflectionClass::newInstanceArgs](reflectionclass.newinstanceargs) — Creates a new class instance from given arguments * [ReflectionClass::newInstanceWithoutConstructor](reflectionclass.newinstancewithoutconstructor) — Creates a new class instance without invoking the constructor * [ReflectionClass::setStaticPropertyValue](reflectionclass.setstaticpropertyvalue) — Sets static property value * [ReflectionClass::\_\_toString](reflectionclass.tostring) — Returns the string representation of the ReflectionClass object
programming_docs
php Gmagick::getimagegreenprimary Gmagick::getimagegreenprimary ============================= (PECL gmagick >= Unknown) Gmagick::getimagegreenprimary — Returns the chromaticy green primary point ### Description ``` public Gmagick::getimagegreenprimary(): array ``` Returns the chromaticity green primary point. Returns an array with the keys "x" and "y". ### Parameters This function has no parameters. ### Return Values Returns an array with the keys "x" and "y" on success. ### Errors/Exceptions Throws an **GmagickException** on error. php ord ord === (PHP 4, PHP 5, PHP 7, PHP 8) ord — Convert the first byte of a string to a value between 0 and 255 ### Description ``` ord(string $character): int ``` Interprets the binary value of the first byte of `character` as an unsigned integer between 0 and 255. If the string is in a single-byte encoding, such as ASCII, ISO-8859, or Windows 1252, this is equivalent to returning the position of a character in the character set's mapping table. However, note that this function is not aware of any string encoding, and in particular will never identify a Unicode code point in a multi-byte encoding such as UTF-8 or UTF-16. This function complements [chr()](function.chr). ### Parameters `character` A character. ### Return Values An integer between 0 and 255. ### Examples **Example #1 **ord()** example** ``` <?php $str = "\n"; if (ord($str) == 10) {     echo "The first character of \$str is a line feed.\n"; } ?> ``` **Example #2 Examining the individual bytes of a UTF-8 string** ``` <?php declare(encoding='UTF-8'); $str = "🐘"; for ( $pos=0; $pos < strlen($str); $pos ++ ) {  $byte = substr($str, $pos);  echo 'Byte ' . $pos . ' of $str has value ' . ord($byte) . PHP_EOL; } ?> ``` The above example will output: Byte 0 of $str has value 240 Byte 1 of $str has value 159 Byte 2 of $str has value 144 Byte 3 of $str has value 152 ### See Also * [chr()](function.chr) - Generate a single-byte string from a number * An [» ASCII-table](https://www.man7.org/linux/man-pages/man7/ascii.7.html) * [mb\_ord()](function.mb-ord) - Get Unicode code point of character * [IntlChar::ord()](intlchar.ord) - Return Unicode code point value of character php DOMElement::getElementsByTagNameNS DOMElement::getElementsByTagNameNS ================================== (PHP 5, PHP 7, PHP 8) DOMElement::getElementsByTagNameNS — Get elements by namespaceURI and localName ### Description ``` public DOMElement::getElementsByTagNameNS(?string $namespace, string $localName): DOMNodeList ``` This function fetch all the descendant elements with a given `localName` and `namespace`. ### Parameters `namespace` The namespace URI. `localName` The local name. Use `*` to return all elements within the element tree. ### Return Values This function returns a new instance of the class [DOMNodeList](class.domnodelist) of all matched elements in the order in which they are encountered in a preorder traversal of this element tree. ### Changelog | Version | Description | | --- | --- | | 8.0.3 | `namespace` is nullable now. | ### See Also * [DOMElement::getElementsByTagName()](domelement.getelementsbytagname) - Gets elements by tagname php FilterIterator::key FilterIterator::key =================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) FilterIterator::key — Get the current key ### Description ``` public FilterIterator::key(): mixed ``` **Warning**This function is currently not documented; only its argument list is available. Get the current key. ### Parameters This function has no parameters. ### Return Values The current key. ### See Also * [FilterIterator::next()](filteriterator.next) - Move the iterator forward * [FilterIterator::current()](filteriterator.current) - Get the current element value php mysqli_stmt::get_warnings mysqli\_stmt::get\_warnings =========================== mysqli\_stmt\_get\_warnings =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) mysqli\_stmt::get\_warnings -- mysqli\_stmt\_get\_warnings — Get result of SHOW WARNINGS ### Description Object-oriented style ``` public mysqli_stmt::get_warnings(): mysqli_warning|false ``` Procedural style ``` mysqli_stmt_get_warnings(mysqli_stmt $statement): mysqli_warning|false ``` **Warning**This function is currently not documented; only its argument list is available. php sodium_crypto_auth sodium\_crypto\_auth ==================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_auth — Compute a tag for the message ### Description ``` sodium_crypto_auth(string $message, string $key): string ``` Symmetric message authentication via **sodium\_crypto\_auth()** provides integrity, but not confidentiality. Unlike with digital signatures (e.g. [sodium\_crypto\_sign\_detached()](function.sodium-crypto-sign-detached)), any party capable of verifying a message is also capable of authenticating their own messages. (Hence, symmetric authentication.) ### Parameters `message` The message you intend to authenticate `key` Authentication key ### Return Values Authentication tag php Gmagick::enhanceimage Gmagick::enhanceimage ===================== (PECL gmagick >= Unknown) Gmagick::enhanceimage — Improves the quality of a noisy image ### Description ``` public Gmagick::enhanceimage(): Gmagick ``` Applies a digital filter that improves the quality of a noisy image. ### Parameters This function has no parameters. ### Return Values The enhanced [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php mysqli::$errno mysqli::$errno ============== mysqli\_errno ============= (PHP 5, PHP 7, PHP 8) mysqli::$errno -- mysqli\_errno — Returns the error code for the most recent function call ### Description Object-oriented style int [$mysqli->errno](mysqli.errno); Procedural style ``` mysqli_errno(mysqli $mysql): int ``` Returns the last error code for the most recent MySQLi function call that can succeed or fail. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values An error code value for the last call, if it failed. zero means no error occurred. ### Examples **Example #1 $mysqli->errno example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if ($mysqli->connect_errno) {     printf("Connect failed: %s\n", $mysqli->connect_error);     exit(); } if (!$mysqli->query("SET a=1")) {     printf("Errorcode: %d\n", $mysqli->errno); } /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } if (!mysqli_query($link, "SET a=1")) {     printf("Errorcode: %d\n", mysqli_errno($link)); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Errorcode: 1193 ``` ### See Also * [mysqli\_connect\_errno()](mysqli.connect-errno) - Returns the error code from last connect call * [mysqli\_connect\_error()](mysqli.connect-error) - Returns a description of the last connection error * [mysqli\_error()](mysqli.error) - Returns a string description of the last error * [mysqli\_sqlstate()](mysqli.sqlstate) - Returns the SQLSTATE error from previous MySQL operation php Imagick::setFont Imagick::setFont ================ (PECL imagick 2 >= 2.1.0, PECL imagick 3) Imagick::setFont — Sets font ### Description ``` public Imagick::setFont(string $font): bool ``` Sets object's font property. This method can be used for example to set font for caption: pseudo-format. The font needs to be configured in ImageMagick configuration or a file by the name of `font` must exist. This method should not be confused with [ImagickDraw::setFont()](imagickdraw.setfont) which sets the font for a specific ImagickDraw object. This method is available if Imagick has been compiled against ImageMagick version 6.3.7 or newer. ### Parameters `font` Font name or a filename ### Return Values Returns **`true`** on success. ### Examples **Example #1 A **Imagick::setFont()** example** Example of using Imagick::setFont ``` <?php /* Create new imagick object */ $im = new Imagick(); /* Set the font for the object */ $im->setFont("example.ttf"); /* Create new caption */ $im->newPseudoImage(100, 100, "caption:Hello"); /* Do something with the image */ ?> ``` ### See Also * [Imagick::getFont()](imagick.getfont) - Gets font * [ImagickDraw::setFont()](imagickdraw.setfont) - Sets the fully-specified font to use when annotating with text * [ImagickDraw::getFont()](imagickdraw.getfont) - Returns the font php gnupg_deletekey gnupg\_deletekey ================ (PECL gnupg >= 0.5) gnupg\_deletekey — Delete a key from the keyring ### Description ``` gnupg_deletekey(resource $identifier, string $key, bool $allow_secret): bool ``` ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. `key` The key to delete. `allow_secret` It specifies whether to delete secret keys as well. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Procedural **gnupg\_deletekey()** example** ``` <?php $res = gnupg_init(); gnupg_deletekey($res, "8660281B6051D071D94B5B230549F9DC851566DC"); ?> ``` **Example #2 OO **gnupg\_deletekey()** example** ``` <?php $gpg = new gnupg(); $gpg->deletekey("8660281B6051D071D94B5B230549F9DC851566DC"); ?> ``` php floatval floatval ======== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) floatval — Get float value of a variable ### Description ``` floatval(mixed $value): float ``` Gets the float value of `value`. ### Parameters `value` May be any scalar type. **floatval()** should not be used on objects, as doing so will emit an **`E_NOTICE`** level error and return 1. ### Return Values The float value of the given variable. Empty arrays return 0, non-empty arrays return 1. Strings will most likely return 0 although this depends on the leftmost characters of the string. The common rules of [float casting](language.types.float#language.types.float.casting) apply. ### Examples **Example #1 **floatval()** Example** ``` <?php $var = '122.34343The'; $float_value_of_var = floatval($var); echo $float_value_of_var; // 122.34343 ?> ``` **Example #2 **floatval()** non-numeric leftmost characters Example** ``` <?php $var = 'The122.34343'; $float_value_of_var = floatval($var); echo $float_value_of_var; // 0 ?> ``` ### See Also * [boolval()](function.boolval) - Get the boolean value of a variable * [intval()](function.intval) - Get the integer value of a variable * [strval()](function.strval) - Get string value of a variable * [settype()](function.settype) - Set the type of a variable * [Type juggling](language.types.type-juggling) php Imagick::setFilename Imagick::setFilename ==================== (PECL imagick 2, PECL imagick 3) Imagick::setFilename — Sets the filename before you read or write the image ### Description ``` public Imagick::setFilename(string $filename): bool ``` Sets the filename before you read or write an image file. ### Parameters `filename` ### Return Values Returns **`true`** on success. php IntlCalendar::setSkippedWallTimeOption IntlCalendar::setSkippedWallTimeOption ====================================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::setSkippedWallTimeOption — Set behavior for handling skipped wall times at positive timezone offset transitions ### Description Object-oriented style ``` public IntlCalendar::setSkippedWallTimeOption(int $option): bool ``` Procedural style ``` intlcal_set_skipped_wall_time_option(IntlCalendar $calendar, int $option): bool ``` Sets the current strategy for dealing with wall times that are skipped whenever the clock is forwarded during dailight saving time start transitions. The default value is **`IntlCalendar::WALLTIME_LAST`** (take it as being the same instant as the one when the wall time is one hour more). Alternative values are **`IntlCalendar::WALLTIME_FIRST`** (same instant as the one with a wall time of one hour less) and **`IntlCalendar::WALLTIME_NEXT_VALID`** (same instant as when DST begins). This affects only the instant represented by the calendar (as reported by [IntlCalendar::getTime()](intlcalendar.gettime)), the field values will not be rewritten accordingly. The calendar must be [lenient](intlcalendar.setlenient) for this option to have any effect, otherwise attempting to set a non-existing time will cause an error. This function requires ICU 4.9 or later. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `option` One of the constants **`IntlCalendar::WALLTIME_FIRST`**, **`IntlCalendar::WALLTIME_LAST`** or **`IntlCalendar::WALLTIME_NEXT_VALID`**. ### Return Values Always returns **`true`**. ### Examples See the example on [IntlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption). ### See Also * [intlCalendar::getSkippedWallTimeOption()](intlcalendar.getskippedwalltimeoption) - Get behavior for handling skipped wall time * [intlCalendar::setRepeatedWallTimeOption()](intlcalendar.setrepeatedwalltimeoption) - Set behavior for handling repeating wall times at negative timezone offset transitions * [intlCalendar::getRepeatedWallTimeOption()](intlcalendar.getrepeatedwalltimeoption) - Get behavior for handling repeating wall time php eio_truncate eio\_truncate ============= (PECL eio >= 0.0.1dev) eio\_truncate — Truncate a file ### Description ``` eio_truncate( string $path, int $offset = 0, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_truncate()** causes the regular file named by `path` to be truncated to a size of precisely `length` bytes ### Parameters `path` File path `offset` Offset from beginning of the file. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values [eio\_busy()](function.eio-busy) returns request resource on success, or **`false`** on failure. ### See Also * [eio\_ftruncate()](function.eio-ftruncate) - Truncate a file php SolrQuery::removeStatsFacet SolrQuery::removeStatsFacet =========================== (PECL solr >= 0.9.2) SolrQuery::removeStatsFacet — Removes one of the stats.facet parameters ### Description ``` public SolrQuery::removeStatsFacet(string $value): SolrQuery ``` Removes one of the stats.facet parameters ### Parameters `value` The value ### Return Values Returns the current SolrQuery object, if the return value is used. php The ResourceBundle class The ResourceBundle class ======================== Introduction ------------ (PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0) Localized software products often require sets of data that are to be customized depending on current locale, e.g.: messages, labels, formatting patterns. ICU resource mechanism allows to define sets of resources that the application can load on locale basis, while accessing them in unified locale-independent fashion. This class implements access to ICU resource data files. These files are binary data arrays which ICU uses to store the localized data. ICU resource bundle can hold simple resources and complex resources. Complex resources are containers which can be either integer-indexed or string-indexed (just like PHP arrays). Simple resources can be of the following types: string, integer, binary data field or integer array. **ResourceBundle** supports direct access to the data through array access pattern and iteration via [foreach](control-structures.foreach), as well as access via class methods. The result will be PHP value for simple resources and **ResourceBundle** object for complex ones. All resources are read-only. Class synopsis -------------- class **ResourceBundle** implements [IteratorAggregate](class.iteratoraggregate), [Countable](class.countable) { /\* Methods \*/ public [\_\_construct](resourcebundle.create)(?string `$locale`, ?string `$bundle`, bool `$fallback` = **`true`**) ``` public count(): int ``` ``` public static create(?string $locale, ?string $bundle, bool $fallback = true): ?ResourceBundle ``` ``` public getErrorCode(): int ``` ``` public getErrorMessage(): string ``` ``` public get(string|int $index, bool $fallback = true): mixed ``` ``` public static getLocales(string $bundle): array|false ``` } Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | **ResourceBundle** implements [IteratorAggregate](class.iteratoraggregate) now. Previously, [Traversable](class.traversable) was implemented instead. | | 7.4.0 | **ResourceBundle** implements [Countable](class.countable) now. | See Also -------- * [» ICU Resource Management](http://userguide.icu-project.org/locale/resources) * [» ICU Data](http://userguide.icu-project.org/icudata) Table of Contents ----------------- * [ResourceBundle::count](resourcebundle.count) — Get number of elements in the bundle * [ResourceBundle::create](resourcebundle.create) — Create a resource bundle * [ResourceBundle::getErrorCode](resourcebundle.geterrorcode) — Get bundle's last error code * [ResourceBundle::getErrorMessage](resourcebundle.geterrormessage) — Get bundle's last error message * [ResourceBundle::get](resourcebundle.get) — Get data from the bundle * [ResourceBundle::getLocales](resourcebundle.locales) — Get supported locales php VarnishLog::getLine VarnishLog::getLine =================== (PECL varnish >= 0.6) VarnishLog::getLine — Get next log line ### Description ``` public VarnishLog::getLine(): array ``` ### Parameters This function has no parameters. ### Return Values Returns an array with the log line data. php pg_update pg\_update ========== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_update — Update table ### Description ``` pg_update( PgSql\Connection $connection, string $table_name, array $values, array $conditions, int $flags = PGSQL_DML_EXEC ): string|bool ``` **pg\_update()** updates records that matches `conditions` with `values`. If `flags` is specified, [pg\_convert()](function.pg-convert) is applied to `values` with the specified flags. By default **pg\_update()** passes raw values. Values must be escaped or the **`PGSQL_DML_ESCAPE`** flag must be specified in `flags`. **`PGSQL_DML_ESCAPE`** quotes and escapes parameters/identifiers. Therefore, table/column names become case sensitive. Note that neither escape nor prepared query can protect LIKE query, JSON, Array, Regex, etc. These parameters should be handled according to their contexts. i.e. Escape/validate values. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. `table_name` Name of the table into which to update rows. `values` An array whose keys are field names in the table `table_name`, and whose values are what matched rows are to be updated to. `conditions` An array whose keys are field names in the table `table_name`, and whose values are the conditions that a row must meet to be updated. `flags` Any number of **`PGSQL_CONV_FORCE_NULL`**, **`PGSQL_DML_NO_CONV`**, **`PGSQL_DML_ESCAPE`**, **`PGSQL_DML_EXEC`**, **`PGSQL_DML_ASYNC`** or **`PGSQL_DML_STRING`** combined. If **`PGSQL_DML_STRING`** is part of the `flags` then query string is returned. When **`PGSQL_DML_NO_CONV`** or **`PGSQL_DML_ESCAPE`** is set, it does not call [pg\_convert()](function.pg-convert) internally. ### Return Values Returns **`true`** on success or **`false`** on failure. Returns string if **`PGSQL_DML_STRING`** is passed via `flags`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_update()** example** ``` <?php    $db = pg_connect('dbname=foo');   $data = array('field1'=>'AA', 'field2'=>'BB');   // This is safe somewhat, since all values are escaped.   // However PostgreSQL supports JSON/Array. These are not   // safe by neither escape nor prepared query.   $res = pg_update($db, 'post_log', $_POST, $data);   if ($res) {       echo "Data is updated: $res\n";   } else {       echo "User must have sent wrong inputs\n";   } ?> ``` ### See Also * [pg\_convert()](function.pg-convert) - Convert associative array values into forms suitable for SQL statements
programming_docs
php DatePeriod::__construct DatePeriod::\_\_construct ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) DatePeriod::\_\_construct — Creates a new DatePeriod object ### Description public **DatePeriod::\_\_construct**( [DateTimeInterface](class.datetimeinterface) `$start`, [DateInterval](class.dateinterval) `$interval`, int `$recurrences`, int `$options` = 0 ) public **DatePeriod::\_\_construct**( [DateTimeInterface](class.datetimeinterface) `$start`, [DateInterval](class.dateinterval) `$interval`, [DateTimeInterface](class.datetimeinterface) `$end`, int `$options` = 0 ) public **DatePeriod::\_\_construct**(string `$isostr`, int `$options` = 0) Creates a new DatePeriod object. [DatePeriod](class.dateperiod) objects can be used as an iterator to generate a number of [DateTimeImmutable](class.datetimeimmutable) or [DateTime](class.datetime) object from a `start` date, a `interval`, and an `end` date or the number of `recurrences`. The class of returned objects is equivalent to the [DateTimeImmutable](class.datetimeimmutable) or [DateTime](class.datetime) ancestor class of the `start` object. ### Parameters `start` The start date of the period. Included by default in the result set. `interval` The interval between recurrences within the period. `recurrences` The number of recurrences. The number of returned results is one higher than this, as the start date is included in the result set by default. Must be greater than `0`. `end` The end date of the period. Excluded by default from the result set. `isostr` A subset of the [» ISO 8601 repeating interval specification](http://en.wikipedia.org/wiki/Iso8601#Repeating_intervals). Examples of some ISO 8601 interval specification features that PHP does not support are: 1. zero occurrences (`R0/`) 2. time offsets other than UTC (`Z`), such as `+02:00`. `options` A bit field which can be used to control certain behaviour with start- and end- dates. With **`DatePeriod::EXCLUDE_START_DATE`** you exclude the start date from the set of recurring dates within the period. With **`DatePeriod::INCLUDE_END_DATE`** you include the end date in the set of recurring dates within the period. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | The **`DatePeriod::INCLUDE_END_DATE`** constant has been added. | | 7.2.19, 7.3.6, 7.4.0 | `recurrences` must be greater than `0` now. | ### Examples **Example #1 DatePeriod example** ``` <?php $start = new DateTime('2012-07-01'); $interval = new DateInterval('P7D'); $end = new DateTime('2012-07-31'); $recurrences = 4; $iso = 'R4/2012-07-01T00:00:00Z/P7D'; // All of these periods are equivalent. $period = new DatePeriod($start, $interval, $recurrences); $period = new DatePeriod($start, $interval, $end); $period = new DatePeriod($iso); // By iterating over the DatePeriod object, all of the // recurring dates within that period are printed. foreach ($period as $date) {     echo $date->format('Y-m-d')."\n"; } ?> ``` The above example will output: ``` 2012-07-01 2012-07-08 2012-07-15 2012-07-22 2012-07-29 ``` **Example #2 DatePeriod example with **`DatePeriod::EXCLUDE_START_DATE`**** ``` <?php $start = new DateTime('2012-07-01'); $interval = new DateInterval('P7D'); $end = new DateTime('2012-07-31'); $period = new DatePeriod($start, $interval, $end,                          DatePeriod::EXCLUDE_START_DATE); // By iterating over the DatePeriod object, all of the // recurring dates within that period are printed. // Note that, in this case, 2012-07-01 is not printed. foreach ($period as $date) {     echo $date->format('Y-m-d')."\n"; } ?> ``` The above example will output: ``` 2012-07-08 2012-07-15 2012-07-22 2012-07-29 ``` **Example #3 DatePeriod example showing all last Thursdays in a year** ``` <?php $begin = new DateTime('2021-12-31'); $end = new DateTime('2022-12-31 23:59:59'); $interval = DateInterval::createFromDateString('last thursday of next month'); $period = new DatePeriod($begin, $interval, $end, DatePeriod::EXCLUDE_START_DATE); foreach ($period as $dt) {     echo $dt->format('l Y-m-d'), "\n"; } ?> ``` The above example will output: ``` Thursday 2022-01-27 Thursday 2022-02-24 Thursday 2022-03-31 Thursday 2022-04-28 Thursday 2022-05-26 Thursday 2022-06-30 Thursday 2022-07-28 Thursday 2022-08-25 Thursday 2022-09-29 Thursday 2022-10-27 Thursday 2022-11-24 Thursday 2022-12-29 ``` ### Notes Unbound numbers of repetitions as specified by ISO 8601 section 4.5 "Recurring time interval" are not supported, i.e. neither passing `"R/..."` as `isostr` nor passing **`null`** as `end` would work. php ReflectionProperty::isDefault ReflectionProperty::isDefault ============================= (PHP 5, PHP 7, PHP 8) ReflectionProperty::isDefault — Checks if property is a default property ### Description ``` public ReflectionProperty::isDefault(): bool ``` Checks whether the property was declared at compile-time, or whether the property was dynamically declared at run-time. ### Parameters This function has no parameters. ### Return Values **`true`** if the property was declared at compile-time, or **`false`** if it was created at run-time. ### Examples **Example #1 **ReflectionProperty::isDefault()** example** ``` <?php class Foo {     public $bar; } $o = new Foo(); $o->bar = 42; $o->baz = 42; $ro = new ReflectionObject($o); var_dump($ro->getProperty('bar')->isDefault()); var_dump($ro->getProperty('baz')->isDefault()); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [ReflectionProperty::getValue()](reflectionproperty.getvalue) - Gets value php Imagick::getImageMimeType Imagick::getImageMimeType ========================= (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::getImageMimeType — Description ### Description ``` public Imagick::getImageMimeType(): string ``` Returns the image mime-type. ### Parameters This function has no parameters. ### Return Values php IntlBreakIterator::getErrorCode IntlBreakIterator::getErrorCode =============================== intl\_get\_error\_code ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlBreakIterator::getErrorCode -- intl\_get\_error\_code — Get last error code on the object ### Description Object-oriented style (method): ``` public IntlBreakIterator::getErrorCode(): int ``` Procedural style: ``` intl_get_error_code(): int ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php ImagickDraw::getFont ImagickDraw::getFont ==================== (PECL imagick 2, PECL imagick 3) ImagickDraw::getFont — Returns the font ### Description ``` public ImagickDraw::getFont(): string ``` **Warning**This function is currently not documented; only its argument list is available. Returns a string specifying the font used when annotating with text. ### Return Values Returns a string on success and false if no font is set. php Imagick::getImageScene Imagick::getImageScene ====================== (PECL imagick 2, PECL imagick 3) Imagick::getImageScene — Gets the image scene ### Description ``` public Imagick::getImageScene(): int ``` Gets the image scene. ### Parameters This function has no parameters. ### Return Values Returns the image scene. ### Errors/Exceptions Throws ImagickException on error. php None Objects and references ---------------------- One of the key-points of PHP OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples. A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn't contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. **Example #1 References and Objects** ``` <?php class A {     public $foo = 1; }   $a = new A; $b = $a;     // $a and $b are copies of the same identifier              // ($a) = ($b) = <id> $b->foo = 2; echo $a->foo."\n"; $c = new A; $d = &$c;    // $c and $d are references              // ($c,$d) = <id> $d->foo = 2; echo $c->foo."\n"; $e = new A; function foo($obj) {     // ($obj) = ($e) = <id>     $obj->foo = 2; } foo($e); echo $e->foo."\n"; ?> ``` The above example will output: ``` 2 2 2 ``` php mysqli::rollback mysqli::rollback ================ mysqli\_rollback ================ (PHP 5, PHP 7, PHP 8) mysqli::rollback -- mysqli\_rollback — Rolls back current transaction ### Description Object-oriented style ``` public mysqli::rollback(int $flags = 0, ?string $name = null): bool ``` Procedural style ``` mysqli_rollback(mysqli $mysql, int $flags = 0, ?string $name = null): bool ``` Rollbacks the current transaction for the database. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `flags` A bitmask of **`MYSQLI_TRANS_COR_*`** constants. `name` If provided then `ROLLBACK/*name*/` is executed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `name` is now nullable. | ### Examples See the [[mysqli::begin\_transaction()](mysqli.begin-transaction) example](mysqli.begin-transaction#mysqli.begin-transaction.example.basic). ### Notes > > **Note**: > > > This function does not work with non transactional table types (like MyISAM or ISAM). > > ### See Also * [mysqli\_begin\_transaction()](mysqli.begin-transaction) - Starts a transaction * [mysqli\_commit()](mysqli.commit) - Commits the current transaction * [mysqli\_autocommit()](mysqli.autocommit) - Turns on or off auto-committing database modifications * [mysqli\_release\_savepoint()](mysqli.release-savepoint) - Removes the named savepoint from the set of savepoints of the current transaction php Imagick::quantizeImages Imagick::quantizeImages ======================= (PECL imagick 2, PECL imagick 3) Imagick::quantizeImages — Analyzes the colors within a sequence of images ### Description ``` public Imagick::quantizeImages( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError ): bool ``` ### Parameters `numberColors` `colorspace` `treedepth` `dither` `measureError` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php date_parse_from_format date\_parse\_from\_format ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) date\_parse\_from\_format — Get info about given date formatted according to the specified format ### Description ``` date_parse_from_format(string $format, string $datetime): array ``` Returns associative array with detailed info about given date/time. ### Parameters `format` Documentation on how the `format` is used, please refer to the documentation of [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat). The same rules apply. `datetime` String representing the date/time. ### Return Values Returns associative array with detailed info about given date/time. The returned array has keys for `year`, `month`, `day`, `hour`, `minute`, `second`, `fraction`, and `is_localtime`. If `is_localtime` is present then `zone_type` indicates the type of timezone. For type `1` (UTC offset) the `zone`, `is_dst` fields are added; for type `2` (abbreviation) the fields `tz_abbr`, `is_dst` are added; and for type `3` (timezone identifier) the `tz_abbr`, `tz_id` are added. The array includes `warning_count` and `warnings` fields. The first one indicate how many warnings there were. The keys of elements `warnings` array indicate the position in the given `datetime` where the warning occurred, with the string value describing the warning itself. An example below shows such a warning. The array also contains `error_count` and `errors` fields. The first one indicate how many errors were found. The keys of elements `errors` array indicate the position in the given `datetime` where the error occurred, with the string value describing the error itself. An example below shows such an error. **Warning** The number of array elements in the `warnings` and `errors` arrays might be less than `warning_count` or `error_count` if they occurred at the same position. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | The `zone` element of the returned array represents seconds instead of minutes now, and its sign is inverted. For instance `-120` is now `7200`. | ### Examples **Example #1 **date\_parse\_from\_format()** example** ``` <?php $date = "6.1.2009 13:00+01:00"; print_r(date_parse_from_format("j.n.Y H:iP", $date)); ?> ``` The above example will output: ``` Array ( [year] => 2009 [month] => 1 [day] => 6 [hour] => 13 [minute] => 0 [second] => 0 [fraction] => [warning_count] => 0 [warnings] => Array ( ) [error_count] => 0 [errors] => Array ( ) [is_localtime] => 1 [zone_type] => 1 [zone] => 3600 [is_dst] => ) ``` **Example #2 **date\_parse\_from\_format()** with warnings example** ``` <?php $date = "26 August 2022 22:30 pm"; $parsed = date_parse_from_format("j F Y G:i a", $date); echo "Warnings count: ", $parsed['warning_count'], "\n"; foreach ($parsed['warnings'] as $position => $message) {     echo "\tOn position {$position}: {$message}\n"; } ?> ``` The above example will output: ``` Warnings count: 1 On position 23: The parsed time was invalid ``` **Example #3 **date\_parse\_from\_format()** with errors example** ``` <?php $date = "26 August 2022 CEST"; $parsed = date_parse_from_format("j F Y H:i", $date); echo "Errors count: ", $parsed['error_count'], "\n"; foreach ($parsed['errors'] as $position => $message) {     echo "\tOn position {$position}: {$message}\n"; } ?> ``` The above example will output: ``` Errors count: 3 On position 15: A two digit hour could not be found On position 19: Data missing ``` ### See Also * [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) - Parses a time string according to a specified format * [checkdate()](function.checkdate) - Validate a Gregorian date php fdf_set_value fdf\_set\_value =============== (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_set\_value — Set the value of a field ### Description ``` fdf_set_value( resource $fdf_document, string $fieldname, mixed $value, int $isName = ? ): bool ``` Sets the `value` for the given field. ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `fieldname` Name of the FDF field, as a string. `value` This parameter will be stored as a string unless it is an array. In this case all array elements will be stored as a value array. `isName` > > **Note**: > > > In older versions of the FDF toolkit last parameter determined if the field value was to be converted to a PDF Name (= 1) or set to a PDF String (= 0). > > The value is no longer used in the current toolkit version 5.0. For compatibility reasons it is still supported as an optional parameter, but ignored internally. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [fdf\_get\_value()](function.fdf-get-value) - Get the value of a field * [fdf\_remove\_item()](function.fdf-remove-item) - Sets target frame for form php spl_autoload spl\_autoload ============= (PHP 5 >= 5.1.0, PHP 7, PHP 8) spl\_autoload — Default implementation for \_\_autoload() ### Description ``` spl_autoload(string $class, ?string $file_extensions = null): void ``` This function is intended to be used as a default implementation for [\_\_autoload()](function.autoload). If nothing else is specified and [spl\_autoload\_register()](function.spl-autoload-register) is called without any parameters then this function will be used for any later call to [\_\_autoload()](function.autoload). ### Parameters `class` The name of the class (and namespace) being instantiated. `file_extensions` By default it checks all include paths to contain filenames built up by the lowercase class name appended by the filename extensions .inc and .php. ### Return Values No value is returned. ### Errors/Exceptions Throws [LogicException](class.logicexception) when the class is not found and there are no other autoloaders registered. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `file_extensions` is now nullable. | php curl_escape curl\_escape ============ (PHP 5 >= 5.5.0, PHP 7, PHP 8) curl\_escape — URL encodes the given string ### Description ``` curl_escape(CurlHandle $handle, string $string): string|false ``` This function URL encodes the given string according to [» RFC 3986](http://www.faqs.org/rfcs/rfc3986). ### Parameters `handle` A cURL handle returned by [curl\_init()](function.curl-init). `string` The string to be encoded. ### Return Values Returns escaped string or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `handle` expects a [CurlHandle](class.curlhandle) instance now; previously, a resource was expected. | ### Examples **Example #1 **curl\_escape()** example** ``` <?php // Create a curl handle $ch = curl_init(); // Escape a string used as a GET parameter $location = curl_escape($ch, 'Hofbräuhaus / München'); // Result: Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen // Compose an URL with the escaped string $url = "http://example.com/add_location.php?location={$location}"; // Result: http://example.com/add_location.php?location=Hofbr%C3%A4uhaus%20%2F%20M%C3%BCnchen // Send HTTP request and close the handle curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_exec($ch); curl_close($ch); ?> ``` ### See Also * [curl\_unescape()](function.curl-unescape) - Decodes the given URL encoded string * [urlencode()](function.urlencode) - URL-encodes string * [rawurlencode()](function.rawurlencode) - URL-encode according to RFC 3986 * [» RFC 3986](http://www.faqs.org/rfcs/rfc3986) php ZipArchive::getExternalAttributesName ZipArchive::getExternalAttributesName ===================================== (PHP 5 >= 5.6.0, PHP 7, PHP 8, PECL zip >= 1.12.4) ZipArchive::getExternalAttributesName — Retrieve the external attributes of an entry defined by its name ### Description ``` public ZipArchive::getExternalAttributesName( string $name, int &$opsys, int &$attr, int $flags = 0 ): bool ``` Retrieve the external attributes of an entry defined by its name. ### Parameters `name` Name of the entry. `opsys` On success, receive the operating system code defined by one of the ZipArchive::OPSYS\_ constants. `attr` On success, receive the external attributes. Value depends on operating system. `flags` If flags is set to **`ZipArchive::FL_UNCHANGED`**, the original unchanged attributes are returned. ### Return Values Returns **`true`** on success or **`false`** on failure.
programming_docs
php mb_convert_encoding mb\_convert\_encoding ===================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_convert\_encoding — Convert a string from one character encoding to another ### Description ``` mb_convert_encoding(array|string $string, string $to_encoding, array|string|null $from_encoding = null): array|string|false ``` Converts `string` from `from_encoding`, or the current internal encoding, to `to_encoding`. If `string` is an array, all its string values will be converted recursively. ### Parameters `string` The string or array to be converted. `to_encoding` The desired encoding of the result. `from_encoding` The current encoding used to interpret `string`. Multiple encodings may be specified as an array or comma separated list, in which case the correct encoding will be guessed using the same algorithm as [mb\_detect\_encoding()](function.mb-detect-encoding). If `from_encoding` is **`null`** or not specified, the [mbstring.internal\_encoding setting](https://www.php.net/manual/en/mbstring.configuration.php#ini.mbstring.internal-encoding) will be used if set, otherwise the [default\_charset setting](https://www.php.net/manual/en/ini.core.php#ini.default-charset). See [supported encodings](https://www.php.net/manual/en/mbstring.supported-encodings.php) for valid values of `to_encoding` and `from_encoding`. ### Return Values The encoded string or array on success, or **`false`** on failure. ### Errors/Exceptions As of PHP 8.0.0, a [ValueError](class.valueerror) is thrown if the value of `to_encoding` or `from_encoding` is an invalid encoding. Prior to PHP 8.0.0, a **`E_WARNING`** was emitted instead. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **mb\_convert\_encoding()** will now throw a [ValueError](class.valueerror) when `to_encoding` is passed an invalid encoding. | | 8.0.0 | **mb\_convert\_encoding()** will now throw a [ValueError](class.valueerror) when `from_encoding` is passed an invalid encoding. | | 8.0.0 | `from_encoding` is nullable now. | | 7.2.0 | This function now also accepts an array as `string`. Formerly, only strings have been supported. | ### Examples **Example #1 **mb\_convert\_encoding()** example** ``` <?php /* Convert internal character encoding to SJIS */ $str = mb_convert_encoding($str, "SJIS"); /* Convert EUC-JP to UTF-7 */ $str = mb_convert_encoding($str, "UTF-7", "EUC-JP"); /* Auto detect encoding from JIS, eucjp-win, sjis-win, then convert str to UCS-2LE */ $str = mb_convert_encoding($str, "UCS-2LE", "JIS, eucjp-win, sjis-win"); /* If mbstring.language is "Japanese", "auto" is expanded to "ASCII,JIS,UTF-8,EUC-JP,SJIS" */ $str = mb_convert_encoding($str, "EUC-JP", "auto"); ?> ``` ### See Also * [mb\_detect\_order()](function.mb-detect-order) - Set/Get character encoding detection order * [UConverter::transcode()](uconverter.transcode) - Convert a string from one character encoding to another * [iconv()](function.iconv) - Convert a string from one character encoding to another php None Callbacks / Callables --------------------- Callbacks can be denoted by the [callable](language.types.callable) type declaration. Some functions like [call\_user\_func()](function.call-user-func) or [usort()](function.usort) accept user-defined callback functions as a parameter. Callback functions can not only be simple functions, but also object methods, including static class methods. ### Passing A PHP function is passed by its name as a string. Any built-in or user-defined function can be used, except language constructs such as: [array()](function.array), [echo](function.echo), [empty()](function.empty), [eval()](function.eval), [exit()](function.exit), [isset()](function.isset), [list()](function.list), [print](function.print) or [unset()](function.unset). A method of an instantiated object is passed as an array containing an object at index 0 and the method name at index 1. Accessing protected and private methods from within a class is allowed. Static class methods can also be passed without instantiating an object of that class by either, passing the class name instead of an object at index 0, or passing `'ClassName::methodName'`. Apart from common user-defined function, [anonymous functions](functions.anonymous) and [arrow functions](functions.arrow) can also be passed to a callback parameter. > > **Note**: > > > As of PHP 8.1.0, anonymous functions can also be created using the [first class callable syntax](functions.first_class_callable_syntax). > > Generally, any object implementing [\_\_invoke()](language.oop5.magic#object.invoke) can also be passed to a callback parameter. **Example #1 Callback function examples** ``` <?php // An example callback function function my_callback_function() {     echo 'hello world!'; } // An example callback method class MyClass {     static function myCallbackMethod() {         echo 'Hello World!';     } } // Type 1: Simple callback call_user_func('my_callback_function'); // Type 2: Static class method call call_user_func(array('MyClass', 'myCallbackMethod')); // Type 3: Object method call $obj = new MyClass(); call_user_func(array($obj, 'myCallbackMethod')); // Type 4: Static class method call call_user_func('MyClass::myCallbackMethod'); // Type 5: Relative static class method call class A {     public static function who() {         echo "A\n";     } } class B extends A {     public static function who() {         echo "B\n";     } } call_user_func(array('B', 'parent::who')); // A // Type 6: Objects implementing __invoke can be used as callables class C {     public function __invoke($name) {         echo 'Hello ', $name, "\n";     } } $c = new C(); call_user_func($c, 'PHP!'); ?> ``` **Example #2 Callback example using a Closure** ``` <?php // Our closure $double = function($a) {     return $a * 2; }; // This is our range of numbers $numbers = range(1, 5); // Use the closure as a callback here to // double the size of each element in our // range $new_numbers = array_map($double, $numbers); print implode(' ', $new_numbers); ?> ``` The above example will output: ``` 2 4 6 8 10 ``` > > **Note**: > > > Callbacks registered with functions such as [call\_user\_func()](function.call-user-func) and [call\_user\_func\_array()](function.call-user-func-array) will not be called if there is an uncaught exception thrown in a previous callback. > > > php ReflectionFunctionAbstract::__clone ReflectionFunctionAbstract::\_\_clone ===================================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::\_\_clone — Clones function ### Description ``` private ReflectionFunctionAbstract::__clone(): void ``` Clones a function. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This method is no longer final. | ### See Also * [Object cloning](language.oop5.cloning) php SolrQuery::addFacetField SolrQuery::addFacetField ======================== (PECL solr >= 0.9.2) SolrQuery::addFacetField — Adds another field to the facet ### Description ``` public SolrQuery::addFacetField(string $field): SolrQuery ``` Adds another field to the facet ### Parameters `field` The name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. ### Examples **Example #1 **SolrQuery::addFacetField()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); $query = new SolrQuery(); $query->setQuery($query); $query->addField('price')->addField('color'); $query->setFacet(true); $query->addFacetField('price')->addFacetField('color'); $query_response = $client->query($query); $response = $query_response->getResponse(); print_r($response['facet_counts']['facet_fields']); ?> ``` The above example will output something similar to: ``` SolrObject Object ( [color] => SolrObject Object ( [blue] => 20 [green] => 100 ) ) ``` php FilterIterator::next FilterIterator::next ==================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) FilterIterator::next — Move the iterator forward ### Description ``` public FilterIterator::next(): void ``` **Warning**This function is currently not documented; only its argument list is available. Move the iterator forward. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [FilterIterator::current()](filteriterator.current) - Get the current element value * [FilterIterator::key()](filteriterator.key) - Get the current key php Yaf_Dispatcher::autoRender Yaf\_Dispatcher::autoRender =========================== (Yaf >=1.0.0) Yaf\_Dispatcher::autoRender — Switch on/off autorendering ### Description ``` public Yaf_Dispatcher::autoRender(bool $flag = ?): Yaf_Dispatcher ``` [Yaf\_Dispatcher](class.yaf-dispatcher) will render automatically after dispatches a incoming request, you can prevent the rendering by calling this method with `flag` **`true`** > > **Note**: > > > you can simply return **`false`** in a action to prevent the auto-rendering of that action > > ### Parameters `flag` bool > > **Note**: > > > since 2.2.0, if this parameter is not given, then the current state will be returned > > ### Return Values ### Examples **Example #1 **Yaf\_Dispatcher::autoRender()** example** ``` <?php class IndexController extends Yaf_Controller_Abstract {      /* init method will be called as soon as a controller is initialized */       public function init() {          if ($this->getRequest()->isXmlHttpRequest()) {              //do not call render for ajax request              //we will outpu a json string              Yaf_Dispatcher::getInstance()->autoRender(FALSE);          }      }  } ?> ``` The above example will output something similar to: php Imagick::getImageGeometry Imagick::getImageGeometry ========================= (PECL imagick 2, PECL imagick 3) Imagick::getImageGeometry — Gets the width and height as an associative array ### Description ``` public Imagick::getImageGeometry(): array ``` Returns the width and height as an associative array. ### Parameters This function has no parameters. ### Return Values Returns an array with the width/height of the image. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::getImageGeometry()**** ``` <?php $imagick = new Imagick(); $imagick->newImage(100, 200, "black"); print_r($imagick->getImageGeometry()); ?> ``` The above example will output: ``` Array ( [width] => 100 [height] => 200 ) ``` php SolrQuery::getExpandQuery SolrQuery::getExpandQuery ========================= (PECL solr >= 2.2.0) SolrQuery::getExpandQuery — Returns the expand query expand.q parameter ### Description ``` public SolrQuery::getExpandQuery(): array ``` Returns the expand query expand.q parameter ### Parameters This function has no parameters. ### Return Values Returns the expand query. php Locale::getDefault Locale::getDefault ================== locale\_get\_default ==================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::getDefault -- locale\_get\_default — Gets the default locale value from the INTL global 'default\_locale' ### Description Object-oriented style ``` public static Locale::getDefault(): string ``` Procedural style ``` locale_get_default(): string ``` Gets the default locale value. At the PHP initialization this value is set to 'intl.default\_locale' value from php.ini if that value exists or from ICU's function uloc\_getDefault(). ### Parameters ### Return Values The current runtime locale ### Examples **Example #1 **locale\_get\_default()** example** ``` <?php ini_set('intl.default_locale', 'de-DE'); echo locale_get_default(); echo '; '; locale_set_default('fr'); echo locale_get_default(); ?> ``` **Example #2 OO example** ``` <?php ini_set('intl.default_locale', 'de-DE'); echo Locale::getDefault(); echo '; '; Locale::setDefault('fr'); echo Locale::getDefault(); ?> ``` The above example will output: ``` de-DE; fr ``` ### See Also * [locale\_set\_default()](locale.setdefault) - Sets the default runtime locale php None else ---- (PHP 4, PHP 5, PHP 7, PHP 8) Often you'd want to execute a statement if a certain condition is met, and a different statement if the condition is not met. This is what `else` is for. `else` extends an `if` statement to execute a statement in case the expression in the `if` statement evaluates to **`false`**. For example, the following code would display a is greater than b if $a is greater than $b, and a is NOT greater than b otherwise: ``` <?php if ($a > $b) {   echo "a is greater than b"; } else {   echo "a is NOT greater than b"; } ?> ``` The `else` statement is only executed if the `if` expression evaluated to **`false`**, and if there were any `elseif` expressions - only if they evaluated to **`false`** as well (see [elseif](control-structures.elseif)). > > **Note**: **Dangling else** > > > > In case of nested `if`-`else` statements, an `else` is always associated with the nearest `if`. > > > > ``` > <?php > $a = false; > $b = true; > if ($a) >     if ($b) >         echo "b"; > else >     echo "c"; > ?> > ``` > Despite the indentation (which does not matter for PHP), the `else` is associated with the `if ($b)`, so the example does not produce any output. While relying on this behavior is valid, it is recommended to avoid it by using curly braces to resolve potential ambiguities. php Imagick::setImageClipMask Imagick::setImageClipMask ========================= (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::setImageClipMask — Sets image clip mask **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::setImageClipMask(Imagick $clip_mask): bool ``` Sets image clip mask from another Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.3.6 or newer. ### Parameters `clip_mask` The Imagick object containing the clip mask ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::setImageClipMask()**** ``` <?php function setImageClipMask($imagePath) {     $imagick = new \Imagick();     $imagick->readImage(realpath($imagePath));     $width = $imagick->getImageWidth();     $height = $imagick->getImageHeight();     $clipMask = new \Imagick();     $clipMask->newPseudoImage(         $width,         $height,         "canvas:transparent"     );     $draw = new \ImagickDraw();     $draw->setFillColor('white');     $draw->circle(         $width / 2,         $height / 2,         ($width / 2) + ($width / 4),         $height / 2     );     $clipMask->drawImage($draw);     $imagick->setImageClipMask($clipMask);     $imagick->negateImage(false);     $imagick->setFormat("png");     header("Content-Type: image/png");     echo $imagick->getImagesBlob();      } ?> ``` php long2ip long2ip ======= (PHP 4, PHP 5, PHP 7, PHP 8) long2ip — Converts an long integer address into a string in (IPv4) Internet standard dotted format ### Description ``` long2ip(int $ip): string|false ``` The function **long2ip()** generates an Internet address in dotted format (i.e.: aaa.bbb.ccc.ddd) from the long integer representation. ### Parameters `ip` A proper address representation in long integer. ### Return Values Returns the Internet IP address as a string, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | The parameter type of `ip` has been changed from string to int. | ### Notes > > **Note**: > > > On 32-bit architectures, casting integer representations of IP addresses from string to int will not give correct results for numbers which exceed **`PHP_INT_MAX`**. > > ### See Also * [ip2long()](function.ip2long) - Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer php SolrParams::get SolrParams::get =============== (PECL solr >= 0.9.2) SolrParams::get — Alias of [SolrParams::getParam()](solrparams.getparam) ### Description ``` final public SolrParams::get(string $param_name): mixed ``` This is an alias for SolrParams::getParam ### Parameters `param_name` Then name of the parameter ### Return Values Returns an array or string depending on the type of parameter php ReflectionExtension::__toString ReflectionExtension::\_\_toString ================================= (PHP 5, PHP 7, PHP 8) ReflectionExtension::\_\_toString — To string ### Description ``` public ReflectionExtension::__toString(): string ``` Exports a reflected extension and returns it as a string. This is the same as the [ReflectionExtension::export()](reflectionextension.export) with the `return` set to **`true`**. ### Parameters This function has no parameters. ### Return Values Returns the exported extension as a string, in the same way as the [ReflectionExtension::export()](reflectionextension.export). ### See Also * [ReflectionExtension::\_\_construct()](reflectionextension.construct) - Constructs a ReflectionExtension * [ReflectionExtension::export()](reflectionextension.export) - Export * [\_\_toString()](language.oop5.magic#object.tostring) php flush flush ===== (PHP 4, PHP 5, PHP 7, PHP 8) flush — Flush system output buffer ### Description ``` flush(): void ``` Flushes the system write buffers of PHP and whatever backend PHP is using (CGI, a web server, etc). This attempts to push current output all the way to the browser with a few caveats. **flush()** may not be able to override the buffering scheme of your web server and it has no effect on any client-side buffering in the browser. It also doesn't affect PHP's userspace output buffering mechanism. This means [ob\_flush()](function.ob-flush) should be called before **flush()** to flush the output buffers if they are in use. Several servers, especially on Win32, will still buffer the output from your script until it terminates before transmitting the results to the browser. Server modules for Apache like mod\_gzip may do buffering of their own that will cause **flush()** to not result in data being sent immediately to the client. Even the browser may buffer its input before displaying it. Netscape, for example, buffers text until it receives an end-of-line or the beginning of a tag, and it won't render tables until the </table> tag of the outermost table is seen. Some versions of Microsoft Internet Explorer will only start to display the page after they have received 256 bytes of output, so you may need to send extra whitespace before flushing to get those browsers to display the page. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [ob\_flush()](function.ob-flush) - Flush (send) the output buffer * [ob\_clean()](function.ob-clean) - Clean (erase) the output buffer * [ob\_end\_flush()](function.ob-end-flush) - Flush (send) the output buffer and turn off output buffering * [ob\_end\_clean()](function.ob-end-clean) - Clean (erase) the output buffer and turn off output buffering
programming_docs
php Imagick::flattenImages Imagick::flattenImages ====================== (PECL imagick 2, PECL imagick 3) Imagick::flattenImages — Merges a sequence of images **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::flattenImages(): Imagick ``` Merges a sequence of images. This is useful for combining Photoshop layers into a single image. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php SVM::train SVM::train ========== (PECL svm >= 0.1.0) SVM::train — Create a SVMModel based on training data ### Description ``` public svm::train(array $problem, array $weights = ?): SVMModel ``` Train a support vector machine based on the supplied training data. ### Parameters `problem` The problem can be provided in three different ways. An array, where the data should start with the class label (usually 1 or -1) then followed by a sparse data set of dimension => data pairs. A URL to a file containing a SVM Light formatted problem, with the each line being a new training example, the start of each line containing the class (1, -1) then a series of tab separated data values shows as key:value. A opened stream pointing to a data source formatted as in the file above. `weights` Weights are an optional set of weighting parameters for the different classes, to help account for unbalanced training sets. For example, if the classes were 1 and -1, and -1 had significantly more example than one, the weight for -1 could be 0.5. Weights should be in the range 0-1. ### Return Values Returns an SVMModel that can be used to classify previously unseen data. Throws SVMException on error php FilesystemIterator::current FilesystemIterator::current =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) FilesystemIterator::current — The current file ### Description ``` public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator ``` Get file information of the current element. ### Parameters This function has no parameters. ### Return Values The filename, file information, or $this depending on the set flags. See the [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants). ### Examples **Example #1 **FilesystemIterator::current()** example** This example will list the contents of the directory containing the script. ``` <?php $iterator = new FilesystemIterator(__DIR__, FilesystemIterator::CURRENT_AS_PATHNAME); foreach ($iterator as $fileinfo) {     echo $iterator->current() . "\n"; } ?> ``` Output of the above example in PHP 8.2 is similar to: ``` /www/examples/. /www/examples/.. /www/examples/apple.jpg /www/examples/banana.jpg /www/examples/example.php ``` ### See Also * [FilesystemIterator constants](class.filesystemiterator#filesystemiterator.constants) * [DirectoryIterator::current()](directoryiterator.current) - Return the current DirectoryIterator item * [DirectoryIterator::getFileName()](directoryiterator.getfilename) - Return file name of current DirectoryIterator item php Ds\Vector::unshift Ds\Vector::unshift ================== (PECL ds >= 1.0.0) Ds\Vector::unshift — Adds values to the front of the vector ### Description ``` public Ds\Vector::unshift(mixed $values = ?): void ``` Adds values to the front of the vector, moving all the current values forward to make room for the new values. ### Parameters `values` The values to add to the front of the vector. > > **Note**: > > > Multiple values will be added in the same order that they are passed. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\Vector::unshift()** example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); $vector->unshift("a"); $vector->unshift("b", "c"); print_r($vector); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => b [1] => c [2] => a [3] => 1 [4] => 2 [5] => 3 ) ``` php curl_multi_strerror curl\_multi\_strerror ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) curl\_multi\_strerror — Return string describing error code ### Description ``` curl_multi_strerror(int $error_code): ?string ``` Returns a text error message describing the given CURLM error code. ### Parameters `error_code` One of the [» CURLM error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) constants. ### Return Values Returns error string for valid error code, **`null`** otherwise. ### Examples **Example #1 **curl\_multi\_strerror()** example** ``` <?php // Create cURL handles $ch1 = curl_init("http://example.com/"); $ch2 = curl_init("http://php.net/"); // Create a cURL multi handle $mh = curl_multi_init(); // Add the handles to the multi handle curl_multi_add_handle($mh, $ch1); curl_multi_add_handle($mh, $ch2); // Execute the multi handle do {     $status = curl_multi_exec($mh, $active);     if ($active) {         curl_multi_select($mh);     } } while ($active && $status === CURLM_OK); // Check for errors if ($status != CURLM_OK) {     // Display error message     echo "ERROR!\n " . curl_multi_strerror($status); } ?> ``` ### See Also * [curl\_strerror()](function.curl-strerror) - Return string describing the given error code * [» cURL error codes](http://curl.haxx.se/libcurl/c/libcurl-errors.html) php Imagick::newPseudoImage Imagick::newPseudoImage ======================= (PECL imagick 2, PECL imagick 3) Imagick::newPseudoImage — Creates a new image ### Description ``` public Imagick::newPseudoImage(int $columns, int $rows, string $pseudoString): bool ``` Creates a new image using ImageMagick pseudo-formats. ### Parameters `columns` columns in the new image `rows` rows in the new image `pseudoString` string containing pseudo image definition. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::newPseudoImage()**** ``` <?php function newPseudoImage($canvasType) {     $imagick = new \Imagick();     $imagick->newPseudoImage(300, 300, $canvasType);     $imagick->setImageFormat("png");     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } //newPseudoImage('gradient:red-rgba(64, 255, 255, 0.5)'); //newPseudoImage("radial-gradient:red-blue"); newPseudoImage("plasma:fractal"); ?> ``` php The Yaf_Response_Abstract class The Yaf\_Response\_Abstract class ================================= Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Response\_Abstract** { /\* Constants \*/ const string DEFAULT\_BODY = "content"; /\* Properties \*/ protected [$\_header](class.yaf-response-abstract#yaf-response-abstract.props.header); protected [$\_body](class.yaf-response-abstract#yaf-response-abstract.props.body); protected [$\_sendheader](class.yaf-response-abstract#yaf-response-abstract.props.sendheader); /\* Methods \*/ public [\_\_construct](yaf-response-abstract.construct)() ``` public appendBody(string $content, string $key = ?): bool ``` ``` public clearBody(string $key = ?): bool ``` ``` public clearHeaders(): void ``` ``` public getBody(string $key = ?): mixed ``` ``` public getHeader(): void ``` ``` public prependBody(string $content, string $key = ?): bool ``` ``` public response(): void ``` ``` protected setAllHeaders(): void ``` ``` public setBody(string $content, string $key = ?): bool ``` ``` public setHeader(string $name, string $value, bool $replace = ?): bool ``` ``` public setRedirect(string $url): bool ``` ``` private __toString(): string ``` public [\_\_destruct](yaf-response-abstract.destruct)() } Properties ---------- \_header \_body \_sendheader Table of Contents ----------------- * [Yaf\_Response\_Abstract::appendBody](yaf-response-abstract.appendbody) — Append to response body * [Yaf\_Response\_Abstract::clearBody](yaf-response-abstract.clearbody) — Discard all exists response body * [Yaf\_Response\_Abstract::clearHeaders](yaf-response-abstract.clearheaders) — Discard all set headers * [Yaf\_Response\_Abstract::\_\_construct](yaf-response-abstract.construct) — The \_\_construct purpose * [Yaf\_Response\_Abstract::\_\_destruct](yaf-response-abstract.destruct) — The \_\_destruct purpose * [Yaf\_Response\_Abstract::getBody](yaf-response-abstract.getbody) — Retrieve a exists content * [Yaf\_Response\_Abstract::getHeader](yaf-response-abstract.getheader) — The getHeader purpose * [Yaf\_Response\_Abstract::prependBody](yaf-response-abstract.prependbody) — The prependBody purpose * [Yaf\_Response\_Abstract::response](yaf-response-abstract.response) — Send response * [Yaf\_Response\_Abstract::setAllHeaders](yaf-response-abstract.setallheaders) — The setAllHeaders purpose * [Yaf\_Response\_Abstract::setBody](yaf-response-abstract.setbody) — Set content to response * [Yaf\_Response\_Abstract::setHeader](yaf-response-abstract.setheader) — Set reponse header * [Yaf\_Response\_Abstract::setRedirect](yaf-response-abstract.setredirect) — The setRedirect purpose * [Yaf\_Response\_Abstract::\_\_toString](yaf-response-abstract.tostring) — Retrieve all bodys as string php Exception Exception ========= Introduction ------------ (PHP 5, PHP 7, PHP 8) **Exception** is the base class for all user exceptions. Class synopsis -------------- class **Exception** implements [Throwable](class.throwable) { /\* Properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/ public [\_\_construct](exception.construct)(string `$message` = "", int `$code` = 0, ?[Throwable](class.throwable) `$previous` = **`null`**) ``` final public getMessage(): string ``` ``` final public getPrevious(): ?Throwable ``` ``` final public getCode(): int ``` ``` final public getFile(): string ``` ``` final public getLine(): int ``` ``` final public getTrace(): array ``` ``` final public getTraceAsString(): string ``` ``` public __toString(): string ``` ``` private __clone(): void ``` } Properties ---------- message The exception message code The exception code file The filename where the exception was created line The line where the exception was created previous The previously thrown exception string The string representation of the stack trace trace The stack trace as an array Table of Contents ----------------- * [Exception::\_\_construct](exception.construct) — Construct the exception * [Exception::getMessage](exception.getmessage) — Gets the Exception message * [Exception::getPrevious](exception.getprevious) — Returns previous Throwable * [Exception::getCode](exception.getcode) — Gets the Exception code * [Exception::getFile](exception.getfile) — Gets the file in which the exception was created * [Exception::getLine](exception.getline) — Gets the line in which the exception was created * [Exception::getTrace](exception.gettrace) — Gets the stack trace * [Exception::getTraceAsString](exception.gettraceasstring) — Gets the stack trace as a string * [Exception::\_\_toString](exception.tostring) — String representation of the exception * [Exception::\_\_clone](exception.clone) — Clone the exception php str_contains str\_contains ============= (PHP 8) str\_contains — Determine if a string contains a given substring ### Description ``` str_contains(string $haystack, string $needle): bool ``` Performs a case-sensitive check indicating if `needle` is contained in `haystack`. ### Parameters `haystack` The string to search in. `needle` The substring to search for in the `haystack`. ### Return Values Returns **`true`** if `needle` is in `haystack`, **`false`** otherwise. ### Examples **Example #1 Using the empty string `''`** ``` <?php if (str_contains('abc', '')) {     echo "Checking the existence of the empty string will always return true"; } ?> ``` The above example will output: ``` Checking the existence of the empty string will always return true ``` **Example #2 Showing case-sensitivity** ``` <?php $string = 'The lazy fox jumped over the fence'; if (str_contains($string, 'lazy')) {     echo "The string 'lazy' was found in the string\n"; } if (str_contains($string, 'Lazy')) {     echo 'The string "Lazy" was found in the string'; } else {     echo '"Lazy" was not found because the case does not match'; } ?> ``` The above example will output: ``` The string 'lazy' was found in the string "Lazy" was not found because the case does not match ``` ### Notes > **Note**: This function is binary-safe. > > ### See Also * [str\_ends\_with()](function.str-ends-with) - Checks if a string ends with a given substring * [str\_starts\_with()](function.str-starts-with) - Checks if a string starts with a given substring * [stripos()](function.stripos) - Find the position of the first occurrence of a case-insensitive substring in a string * [strrpos()](function.strrpos) - Find the position of the last occurrence of a substring in a string * [strripos()](function.strripos) - Find the position of the last occurrence of a case-insensitive substring in a string * [strstr()](function.strstr) - Find the first occurrence of a string * [strpbrk()](function.strpbrk) - Search a string for any of a set of characters * [substr()](function.substr) - Return part of a string * [preg\_match()](function.preg-match) - Perform a regular expression match php SolrClient::optimize SolrClient::optimize ==================== (PECL solr >= 0.9.2) SolrClient::optimize — Defragments the index ### Description ``` public SolrClient::optimize(int $maxSegments = 1, bool $softCommit = true, bool $waitSearcher = true): SolrUpdateResponse ``` Defragments the index for faster search performance. ### Parameters `maxSegments` Optimizes down to at most this number of segments. Since Solr 1.3 `softCommit` This will refresh the 'view' of the index in a more performant manner, but without "on-disk" guarantees. (Solr4.0+) `waitSearcher` Block until a new searcher is opened and registered as the main query searcher, making the changes visible. ### Return Values Returns a SolrUpdateResponse on success or throws an exception on failure. ### Errors/Exceptions Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to process the request. ### Notes **Warning** PECL Solr >= 2.0 only supports Solr Server >= 4.0 Prior to PECL Solr 2.0 this method used to accept these arguments "int $maxSegments, bool $waitFlush, bool $waitSearcher". ### See Also * [SolrClient::commit()](solrclient.commit) - Finalizes all add/deletes made to the index * [SolrClient::rollback()](solrclient.rollback) - Rollbacks all add/deletes made to the index since the last commit php pspell_config_ignore pspell\_config\_ignore ====================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_config\_ignore — Ignore words less than N characters long ### Description ``` pspell_config_ignore(PSpell\Config $config, int $min_length): bool ``` **pspell\_config\_ignore()** should be used on a config before calling [pspell\_new\_config()](function.pspell-new-config). This function allows short words to be skipped by the spell checker. ### Parameters `config` An [PSpell\Config](class.pspell-config) instance. `min_length` Words less than `min_length` characters will be skipped. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `config` parameter expects an [PSpell\Config](class.pspell-config) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pspell\_config\_ignore()**** ``` <?php $pspell_config = pspell_config_create("en"); pspell_config_ignore($pspell_config, 5); $pspell = pspell_new_config($pspell_config); pspell_check($pspell, "abcd");    //will not result in an error ?> ``` php Parle\RParser::advance Parle\RParser::advance ====================== (PECL parle >= 0.7.0) Parle\RParser::advance — Process next parser rule ### Description ``` public Parle\RParser::advance(): void ``` Prosess next parser rule. ### Parameters This function has no parameters. ### Return Values No value is returned. php date_timezone_get date\_timezone\_get =================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) date\_timezone\_get — Alias of [DateTime::getTimezone()](datetime.gettimezone) ### Description This function is an alias of: [DateTime::getTimezone()](datetime.gettimezone) php filemtime filemtime ========= (PHP 4, PHP 5, PHP 7, PHP 8) filemtime — Gets file modification time ### Description ``` filemtime(string $filename): int|false ``` This function returns the time when the data blocks of a file were being written to, that is, the time when the content of the file was changed. ### Parameters `filename` Path to the file. ### Return Values Returns the time the file was last modified, or **`false`** on failure. The time is returned as a Unix timestamp, which is suitable for the [date()](function.date) function. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 **filemtime()** example** ``` <?php // outputs e.g.  somefile.txt was last modified: December 29 2002 22:16:23. $filename = 'somefile.txt'; if (file_exists($filename)) {     echo "$filename was last modified: " . date ("F d Y H:i:s.", filemtime($filename)); } ?> ``` ### Notes > > **Note**: > > > Note that time resolution may differ from one file system to another. > > > > **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details. > > **Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [filectime()](function.filectime) - Gets inode change time of file * [stat()](function.stat) - Gives information about a file * [touch()](function.touch) - Sets access and modification time of file * [getlastmod()](function.getlastmod) - Gets time of last page modification php Yaf_View_Simple::display Yaf\_View\_Simple::display ========================== (Yaf >=1.0.0) Yaf\_View\_Simple::display — Render and display ### Description ``` public Yaf_View_Simple::display(string $tpl, array $tpl_vars = ?): bool ``` Render a template and display the result instantly. ### Parameters `tpl` `tpl_vars` ### Return Values php SplDoublyLinkedList::count SplDoublyLinkedList::count ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::count — Counts the number of elements in the doubly linked list ### Description ``` public SplDoublyLinkedList::count(): int ``` ### Parameters This function has no parameters. ### Return Values Returns the number of elements in the doubly linked list.
programming_docs
php RecursiveIteratorIterator::getInnerIterator RecursiveIteratorIterator::getInnerIterator =========================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) RecursiveIteratorIterator::getInnerIterator — Get inner iterator ### Description ``` public RecursiveIteratorIterator::getInnerIterator(): RecursiveIterator ``` Gets the current active sub iterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The current active sub iterator. php mb_substr mb\_substr ========== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_substr — Get part of string ### Description ``` mb_substr( string $string, int $start, ?int $length = null, ?string $encoding = null ): string ``` Performs a multi-byte safe [substr()](function.substr) operation based on number of characters. Position is counted from the beginning of `string`. First character's position is 0. Second character position is 1, and so on. ### Parameters `string` The string to extract the substring from. `start` If `start` is non-negative, the returned string will start at the `start`'th position in `string`, counting from zero. For instance, in the string '`abcdef`', the character at position `0` is '`a`', the character at position `2` is '`c`', and so forth. If `start` is negative, the returned string will start at the `start`'th character from the end of `string`. `length` Maximum number of characters to use from `string`. If omitted or `NULL` is passed, extract all characters to the end of the string. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values **mb\_substr()** returns the portion of `string` specified by the `start` and `length` parameters. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | ### See Also * [mb\_strcut()](function.mb-strcut) - Get part of string * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding php ReflectionClass::getExtensionName ReflectionClass::getExtensionName ================================= (PHP 5, PHP 7, PHP 8) ReflectionClass::getExtensionName — Gets the name of the extension which defined the class ### Description ``` public ReflectionClass::getExtensionName(): string|false ``` Gets the name of the extension which defined the class. ### Parameters This function has no parameters. ### Return Values The name of the extension which defined the class, or **`false`** for user-defined classes. ### Examples **Example #1 Basic usage of **ReflectionClass::getExtensionName()**** ``` <?php $class = new ReflectionClass('ReflectionClass'); $extension = $class->getExtensionName(); var_dump($extension); ?> ``` The above example will output: ``` string(10) "Reflection" ``` ### See Also * [ReflectionClass::getExtension()](reflectionclass.getextension) - Gets a ReflectionExtension object for the extension which defined the class php Gmagick::minifyimage Gmagick::minifyimage ==================== (PECL gmagick >= Unknown) Gmagick::minifyimage — Scales an image proportionally to half its size ### Description ``` public Gmagick::minifyimage(): Gmagick ``` A convenient method that scales an image proportionally to one-half its original size. ### Parameters This function has no parameters. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php ibase_errcode ibase\_errcode ============== (PHP 5, PHP 7 < 7.4.0) ibase\_errcode — Return an error code ### Description ``` ibase_errcode(): int ``` Returns the error code that resulted from the most recent InterBase function call. ### Parameters This function has no parameters. ### Return Values Returns the error code as an integer, or **`false`** if no error occurred. ### See Also * [ibase\_errmsg()](function.ibase-errmsg) - Return error messages php ReflectionExtension::info ReflectionExtension::info ========================= (PHP 5 >= 5.2.4, PHP 7, PHP 8) ReflectionExtension::info — Print extension info ### Description ``` public ReflectionExtension::info(): void ``` Prints out the "[phpinfo()](function.phpinfo)" snippet for the given extension. ### Parameters This function has no parameters. ### Return Values Information about the extension. ### Examples **Example #1 **ReflectionExtension::info()** example** ``` <?php $ext = new ReflectionExtension('mysqli'); $ext->info(); ?> ``` The above example will output something similar to: ``` mysqli MysqlI Support => enabled Client API library version => mysqlnd 5.0.5-dev - 081106 - $Revision$ Active Persistent Links => 0 Inactive Persistent Links => 0 Active Links => 0 Persistent cache => enabled put_hits => 0 put_misses => 0 get_hits => 0 get_misses => 0 size => 2000 free_items => 2000 references => 2 Directive => Local Value => Master Value mysqli.max_links => Unlimited => Unlimited mysqli.max_persistent => Unlimited => Unlimited mysqli.allow_persistent => On => On mysqli.default_host => no value => no value mysqli.default_user => no value => no value mysqli.default_pw => no value => no value mysqli.default_port => 3306 => 3306 mysqli.default_socket => no value => no value mysqli.reconnect => Off => Off mysqli.allow_local_infile => On => On mysqli.cache_size => 2000 => 2000 ``` ### See Also * [ReflectionExtension::getName()](reflectionextension.getname) - Gets extension name * [phpinfo()](function.phpinfo) - Outputs information about PHP's configuration php geoip_country_name_by_name geoip\_country\_name\_by\_name ============================== (PECL geoip >= 0.2.0) geoip\_country\_name\_by\_name — Get the full country name ### Description ``` geoip_country_name_by_name(string $hostname): string ``` The **geoip\_country\_name\_by\_name()** function will return the full country name corresponding to a hostname or an IP address. ### Parameters `hostname` The hostname or IP address whose location is to be looked-up. ### Return Values Returns the country name on success, or **`false`** if the address cannot be found in the database. ### Examples **Example #1 A **geoip\_country\_name\_by\_name()** example** This will print where the host example.com is located. ``` <?php $country = geoip_country_name_by_name('www.example.com'); if ($country) {     echo 'This host is located in: ' . $country; } ?> ``` The above example will output: ``` This host is located in: United States ``` ### See Also * [geoip\_country\_code\_by\_name()](function.geoip-country-code-by-name) - Get the two letter country code * [geoip\_country\_code3\_by\_name()](function.geoip-country-code3-by-name) - Get the three letter country code php DOMNode::isSameNode DOMNode::isSameNode =================== (PHP 5, PHP 7, PHP 8) DOMNode::isSameNode — Indicates if two nodes are the same node ### Description ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` This function indicates if two nodes are the same node. The comparison is *not* based on content ### Parameters `otherNode` The compared node. ### Return Values Returns **`true`** on success or **`false`** on failure. php EventBufferEvent::close EventBufferEvent::close ======================= (PECL event >= 1.10.0) EventBufferEvent::close — Closes file descriptor associated with the current buffer event ### Description ``` public EventBufferEvent::close(): void ``` Closes file descriptor associated with the current buffer event. This method may be used in cases when the **`EventBufferEvent::OPT_CLOSE_ON_FREE`** option is not appropriate. ### Parameters This function has no parameters. ### Return Values No value is returned. php SyncReaderWriter::__construct SyncReaderWriter::\_\_construct =============================== (PECL sync >= 1.0.0) SyncReaderWriter::\_\_construct — Constructs a new SyncReaderWriter object ### Description ``` public SyncReaderWriter::__construct(string $name = ?, int $autounlock = 1) ``` Constructs a named or unnamed reader-writer object. ### Parameters `name` The name of the reader-writer if this is a named reader-writer object. > > **Note**: > > > If the name already exists, it must be able to be opened by the current user that the process is running as or an exception will be thrown with a meaningless error message. > > > **Note**: On Windows, `name` must not contain backslashes. > > `autounlock` Specifies whether or not to automatically unlock the reader-writer at the conclusion of the PHP script. **Warning** If an object is: A named reader-writer with an autounlock of FALSE, the object is locked for either reading or writing, and the PHP script concludes before the object is unlocked, then the underlying objects will end up in an inconsistent state. ### Return Values The new [SyncReaderWriter](class.syncreaderwriter) object. ### Errors/Exceptions An exception is thrown if the reader-writer cannot be created or opened. ### Examples **Example #1 **SyncReaderWriter::\_\_construct()** example** ``` <?php $readwrite = new SyncReaderWriter("FileCacheLock"); $readwrite->readlock(); /* ... */ $readwrite->readunlock(); $readwrite->writelock(); /* ... */ $readwrite->writeunlock(); ?> ``` ### See Also * [SyncReaderWriter::readlock()](syncreaderwriter.readlock) - Waits for a read lock * [SyncReaderWriter::readunlock()](syncreaderwriter.readunlock) - Releases a read lock * [SyncReaderWriter::writelock()](syncreaderwriter.writelock) - Waits for an exclusive write lock * [SyncReaderWriter::writeunlock()](syncreaderwriter.writeunlock) - Releases a write lock php pg_fetch_all pg\_fetch\_all ============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) pg\_fetch\_all — Fetches all rows from a result as an array ### Description ``` pg_fetch_all(PgSql\Result $result, int $mode = PGSQL_ASSOC): array ``` **pg\_fetch\_all()** returns an array that contains all rows (records) in the [PgSql\Result](class.pgsql-result) instance. > **Note**: This function sets NULL fields to the PHP **`null`** value. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `mode` An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: **`PGSQL_ASSOC`**, **`PGSQL_NUM`** and **`PGSQL_BOTH`**. Using **`PGSQL_NUM`**, the function will return an array with numerical indices, using **`PGSQL_ASSOC`** it will return only associative indices while **`PGSQL_BOTH`** will return both numerical and associative indices. ### Return Values An array with all rows in the result. Each row is an array of field values indexed by field name. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | **pg\_fetch\_all()** will now return an empty array instead of **`false`** for result sets with zero rows. | | 7.1.0 | The `mode` parameter was added. | ### Examples **Example #1 PostgreSQL fetch all** ``` <?php  $conn = pg_pconnect("dbname=publisher"); if (!$conn) {     echo "An error occurred.\n";     exit; } $result = pg_query($conn, "SELECT * FROM authors"); if (!$result) {     echo "An error occurred.\n";     exit; } $arr = pg_fetch_all($result); print_r($arr); ?> ``` The above example will output something similar to: ``` Array ( [0] => Array ( [id] => 1 [name] => Fred ) [1] => Array ( [id] => 2 [name] => Bob ) ) ``` ### See Also * [pg\_fetch\_row()](function.pg-fetch-row) - Get a row as an enumerated array * [pg\_fetch\_array()](function.pg-fetch-array) - Fetch a row as an array * [pg\_fetch\_object()](function.pg-fetch-object) - Fetch a row as an object * [pg\_fetch\_result()](function.pg-fetch-result) - Returns values from a result instance php Imagick::getVersion Imagick::getVersion =================== (PECL imagick 2, PECL imagick 3) Imagick::getVersion — Returns the ImageMagick API version ### Description ``` public static Imagick::getVersion(): array ``` Returns the ImageMagick API version as a string and as a number. ### Parameters This function has no parameters. ### Return Values Returns the ImageMagick API version as a string and as a number. ### Errors/Exceptions Throws ImagickException on error. php geoip_org_by_name geoip\_org\_by\_name ==================== (PECL geoip >= 0.2.0) geoip\_org\_by\_name — Get the organization name ### Description ``` geoip_org_by_name(string $hostname): string ``` The **geoip\_org\_by\_name()** function will return the name of the organization that an IP is assigned to. This function is currently only available to users who have bought a commercial GeoIP Organization, ISP or AS Edition. A warning will be issued if the proper database cannot be located. ### Parameters `hostname` The hostname or IP address. ### Return Values Returns the organization name on success, or **`false`** if the address cannot be found in the database. ### Examples **Example #1 A **geoip\_org\_by\_name()** example** This will print to whom the host example.com IP is allocated. ``` <?php $org = geoip_org_by_name('www.example.com'); if ($org) {     echo 'This host IP is allocated to: ' . $org; } ?> ``` The above example will output: ``` This host IP is allocated to: ICANN c/o Internet Assigned Numbers Authority ``` php $argc $argc ===== (PHP 4, PHP 5, PHP 7, PHP 8) $argc — The number of arguments passed to script ### Description Contains the number of arguments passed to the current script when running from the [command line](https://www.php.net/manual/en/features.commandline.php). > **Note**: The script's filename is always passed as an argument to the script, therefore the minimum value of $argc is `1`. > > > **Note**: This variable is not available when [register\_argc\_argv](https://www.php.net/manual/en/ini.core.php#ini.register-argc-argv) is disabled. > > ### Examples **Example #1 $argc example** ``` <?php var_dump($argc); ?> ``` When executing the example with: php script.php arg1 arg2 arg3 The above example will output something similar to: ``` int(4) ``` ### Notes > > **Note**: > > > This is also available as [$\_SERVER['argc']](reserved.variables.server). > > ### See Also * [getopt()](function.getopt) - Gets options from the command line argument list * [[$argv](reserved.variables.argv)](reserved.variables.argv) php IntlCalendar::getMaximum IntlCalendar::getMaximum ======================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getMaximum — Get the global maximum value for a field ### Description Object-oriented style ``` public IntlCalendar::getMaximum(int $field): int|false ``` Procedural style ``` intlcal_get_maximum(IntlCalendar $calendar, int $field): int|false ``` Gets the global maximum for a field, in this specific calendar. This value is larger or equal to that returned by [IntlCalendar::getActualMaximum()](intlcalendar.getactualmaximum), which is in its turn larger or equal to that returned by [IntlCalendar::getLeastMaximum()](intlcalendar.getleastmaximum). ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `field` One of the [IntlCalendar](class.intlcalendar) date/time [field constants](class.intlcalendar#intlcalendar.constants). These are integer values between `0` and **`IntlCalendar::FIELD_COUNT`**. ### Return Values An int representing a field value in the fieldʼs unit or **`false`** on failure. ### See Also * [IntlCalendar::getActualMaximum()](intlcalendar.getactualmaximum) - The maximum value for a field, considering the objectʼs current time * [IntlCalendar::getLeastMaximum()](intlcalendar.getleastmaximum) - Get the smallest local maximum for a field * [IntlCalendar::getMinimum()](intlcalendar.getminimum) - Get the global minimum value for a field php SplQueue::dequeue SplQueue::dequeue ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplQueue::dequeue — Dequeues a node from the queue ### Description ``` public SplQueue::dequeue(): mixed ``` Dequeues `value` from the top of the queue. > > **Note**: > > > **SplQueue::dequeue()** is an alias of [SplDoublyLinkedList::shift()](spldoublylinkedlist.shift). > > ### Parameters This function has no parameters. ### Return Values The value of the dequeued node. php ImagickDraw::getFontStretch ImagickDraw::getFontStretch =========================== (PECL imagick 2 >=2.3.0, PECL imagick 3) ImagickDraw::getFontStretch — Description ### Description ``` public ImagickDraw::getFontStretch(): int ``` Gets the font stretch to use when annotating with text. Returns a StretchType. ### Parameters This function has no parameters. ### Return Values php register_tick_function register\_tick\_function ======================== (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) register\_tick\_function — Register a function for execution on each tick ### Description ``` register_tick_function(callable $callback, mixed ...$args): bool ``` Registers the given `callback` to be executed when a [tick](control-structures.declare#control-structures.declare.ticks) is called. ### Parameters `callback` The function to register. `args` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **register\_tick\_function()** example** ``` <?php declare(ticks=1); // using a function as the callback register_tick_function('my_function', true); // using an object->method $object = new my_class(); register_tick_function(array($object, 'my_method'), true); ?> ``` ### See Also * [declare](control-structures.declare) * [unregister\_tick\_function()](function.unregister-tick-function) - De-register a function for execution on each tick php SolrCollapseFunction::__construct SolrCollapseFunction::\_\_construct =================================== (PECL solr >= 2.2.0) SolrCollapseFunction::\_\_construct — Constructor ### Description public **SolrCollapseFunction::\_\_construct**(string `$field` = ?) Collapse Function constructor ### Parameters `field` The field name to collapse on. In order to collapse a result. The field type must be a single valued String, Int or Float. ### Examples **Example #1 **SolrCollapseFunction::\_\_construct()** example** ``` <?php include "bootstrap.php"; $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT,     'path'     => SOLR_SERVER_PATH ); $client = new SolrClient($options); $query = new SolrQuery('*:*'); $func = new SolrCollapseFunction('field_name'); $func->setMax('sum(cscore(),field(some_other_field))'); $func->setSize(100); $func->setNullPolicy(SolrCollapseFunction::NULLPOLICY_EXPAND); $query->collapse($func); $queryResponse = $client->query($query); $response = $queryResponse->getResponse(); print_r($response); ?> ``` ### See Also * [SolrQuery::collapse()](solrquery.collapse) - Collapses the result set to a single document per group
programming_docs
php ReflectionClass::isInstantiable ReflectionClass::isInstantiable =============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::isInstantiable — Checks if the class is instantiable ### Description ``` public ReflectionClass::isInstantiable(): bool ``` Checks if the class is instantiable. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ReflectionClass::isInstantiable()** example** ``` <?php class C { } interface iface {     function f1(); } class ifaceImpl implements iface {     function f1() {} } abstract class abstractClass {     function f1() { }     abstract function f2(); } class D extends abstractClass {     function f2() { } } trait T {     function f1() {} } class privateConstructor {     private function __construct() { } } $classes = array(     "C",     "iface",     "ifaceImpl",     "abstractClass",     "D",     "T",     "privateConstructor", ); foreach($classes  as $class ) {     $reflectionClass = new ReflectionClass($class);     echo "Is $class instantiable?  ";     var_dump($reflectionClass->isInstantiable());  } ?> ``` The above example will output: ``` Is C instantiable? bool(true) Is iface instantiable? bool(false) Is ifaceImpl instantiable? bool(true) Is abstractClass instantiable? bool(false) Is D instantiable? bool(true) Is T instantiable? bool(false) Is privateConstructor instantiable? bool(false) ``` ### See Also * [ReflectionClass::isInstance()](reflectionclass.isinstance) - Checks class for instance php Imagick::pingImageFile Imagick::pingImageFile ====================== (PECL imagick 2, PECL imagick 3) Imagick::pingImageFile — Get basic image attributes in a lightweight manner ### Description ``` public Imagick::pingImageFile(resource $filehandle, string $fileName = ?): bool ``` This method can be used to query image width, height, size, and format without reading the whole image to memory. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `filehandle` An open filehandle to the image. `fileName` Optional filename for this image. ### Return Values Returns **`true`** on success. ### Examples **Example #1 Using **Imagick::pingImageFile()**** Opening a remote location ``` <?php /* fopen a remote location */ $fp = fopen("http://example.com/test.jpg"); /* create new imagick object */ $im = new Imagick(); /* pass the handle to imagick */ $im->pingImageFile($fp); ?> ``` ### See Also * [Imagick::pingImage()](imagick.pingimage) - Fetch basic attributes about the image * [Imagick::pingImageBlob()](imagick.pingimageblob) - Quickly fetch attributes * [Imagick::readImage()](imagick.readimage) - Reads image from filename * [Imagick::readImageBlob()](imagick.readimageblob) - Reads image from a binary string * [Imagick::readImageFile()](imagick.readimagefile) - Reads image from open filehandle php Yaf_Request_Http::getCookie Yaf\_Request\_Http::getCookie ============================= (Yaf >=1.0.0) Yaf\_Request\_Http::getCookie — Retrieve Cookie variable ### Description ``` public Yaf_Request_Http::getCookie(string $name, string $default = ?): mixed ``` Retrieve Cookie variable ### Parameters `name` the cookie name `default` if this parameter is provide, this will be returned if the cookie can not be found ### Return Values ### See Also * [Yaf\_Request\_Http::get()](yaf-request-http.get) - Retrieve variable from client * [Yaf\_Request\_Http::getQuery()](yaf-request-http.getquery) - Fetch a query parameter * [Yaf\_Request\_Http::getPost()](yaf-request-http.getpost) - Retrieve POST variable * [Yaf\_Request\_Http::getRaw()](yaf-request-http.getraw) - Retrieve Raw request body * [Yaf\_Request\_Abstract::getServer()](yaf-request-abstract.getserver) - Retrieve SERVER variable * [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) - Retrieve calling parameter php Phar::canCompress Phar::canCompress ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::canCompress — Returns whether phar extension supports compression using either zlib or bzip2 ### Description ``` final public static Phar::canCompress(int $compression = 0): bool ``` This should be used to test whether compression is possible prior to loading a phar archive containing compressed files. ### Parameters `compression` Either `Phar::GZ` or `Phar::BZ2` can be used to test whether compression is possible with a specific compression algorithm (zlib or bzip2). ### Return Values **`true`** if compression/decompression is available, **`false`** if not. ### Examples **Example #1 A **Phar::canCompress()** example** ``` <?php if (Phar::canCompress()) {     echo file_get_contents('phar://compressedphar.phar/internal/file.txt'); } else {     echo 'no compression available'; } ?> ``` ### See Also * [PharFileInfo::getCompressedSize()](pharfileinfo.getcompressedsize) - Returns the actual size of the file (with compression) inside the Phar archive * [PharFileInfo::isCompressed()](pharfileinfo.iscompressed) - Returns whether the entry is compressed * [PharFileInfo::compress()](pharfileinfo.compress) - Compresses the current Phar entry with either zlib or bzip2 compression * [PharFileInfo::decompress()](pharfileinfo.decompress) - Decompresses the current Phar entry within the phar * [Phar::isCompressed()](phar.iscompressed) - Returns Phar::GZ or PHAR::BZ2 if the entire phar archive is compressed (.tar.gz/tar.bz and so on) * [Phar::compressFiles()](phar.compressfiles) - Compresses all files in the current Phar archive * [Phar::decompressFiles()](phar.decompressfiles) - Decompresses all files in the current Phar archive * [Phar::getSupportedCompression()](phar.getsupportedcompression) - Return array of supported compression algorithms * [Phar::convertToExecutable()](phar.converttoexecutable) - Convert a phar archive to another executable phar archive file format * [Phar::convertToData()](phar.converttodata) - Convert a phar archive to a non-executable tar or zip file php stream_socket_recvfrom stream\_socket\_recvfrom ======================== (PHP 5, PHP 7, PHP 8) stream\_socket\_recvfrom — Receives data from a socket, connected or not ### Description ``` stream_socket_recvfrom( resource $socket, int $length, int $flags = 0, ?string &$address = null ): string|false ``` **stream\_socket\_recvfrom()** accepts data from a remote socket up to `length` bytes. ### Parameters `socket` The remote socket. `length` The number of bytes to receive from the `socket`. `flags` The value of `flags` can be any combination of the following: **Possible values for `flags`**| **`STREAM_OOB`** | Process OOB (`out-of-band`) data. | | **`STREAM_PEEK`** | Retrieve data from the socket, but do not consume the buffer. Subsequent calls to [fread()](function.fread) or **stream\_socket\_recvfrom()** will see the same data. | `address` If `address` is provided it will be populated with the address of the remote socket. ### Return Values Returns the read data, as a string, or **`false`** on failure. ### Examples **Example #1 **stream\_socket\_recvfrom()** example** ``` <?php /* Open a server socket to port 1234 on localhost */ $server = stream_socket_server('tcp://127.0.0.1:1234'); /* Accept a connection */ $socket = stream_socket_accept($server); /* Grab a packet (1500 is a typical MTU size) of OOB data */ echo "Received Out-Of-Band: '" . stream_socket_recvfrom($socket, 1500, STREAM_OOB) . "'\n"; /* Take a peek at the normal in-band data, but don't consume it. */ echo "Data: '" . stream_socket_recvfrom($socket, 1500, STREAM_PEEK) . "'\n"; /* Get the exact same packet again, but remove it from the buffer this time. */ echo "Data: '" . stream_socket_recvfrom($socket, 1500) . "'\n"; /* Close it up */ fclose($socket); fclose($server); ?> ``` ### Notes > > **Note**: > > > If a message received is longer than the `length` parameter, excess bytes may be discarded depending on the type of socket the message is received from (such as UDP). > > > > **Note**: > > > Calls to **stream\_socket\_recvfrom()** on socket-based streams, after calls to buffer-based stream functions (like [fread()](function.fread) or [stream\_get\_line()](function.stream-get-line)) read data directly from the socket and bypass the stream buffer. > > ### See Also * [stream\_socket\_sendto()](function.stream-socket-sendto) - Sends a message to a socket, whether it is connected or not * [stream\_socket\_client()](function.stream-socket-client) - Open Internet or Unix domain socket connection * [stream\_socket\_server()](function.stream-socket-server) - Create an Internet or Unix domain server socket php DOMElement::setIdAttributeNS DOMElement::setIdAttributeNS ============================ (PHP 5, PHP 7, PHP 8) DOMElement::setIdAttributeNS — Declares the attribute specified by local name and namespace URI to be of type ID ### Description ``` public DOMElement::setIdAttributeNS(string $namespace, string $qualifiedName, bool $isId): void ``` Declares the attribute specified by `qualifiedName` and `namespace` to be of type ID. ### Parameters `namespace` The namespace URI of the attribute. `qualifiedName` The local name of the attribute, as `prefix:tagname`. `isId` Set it to **`true`** if you want `name` to be of type ID, **`false`** otherwise. ### Return Values No value is returned. ### Errors/Exceptions **`DOM_NO_MODIFICATION_ALLOWED_ERR`** Raised if the node is readonly. **`DOM_NOT_FOUND`** Raised if `name` is not an attribute of this element. ### See Also * [DOMDocument::getElementById()](domdocument.getelementbyid) - Searches for an element with a certain id * [DOMElement::setIdAttribute()](domelement.setidattribute) - Declares the attribute specified by name to be of type ID * [DOMElement::setIdAttributeNode()](domelement.setidattributenode) - Declares the attribute specified by node to be of type ID php SolrQuery::setFacetMissing SolrQuery::setFacetMissing ========================== (PECL solr >= 0.9.2) SolrQuery::setFacetMissing — Maps to facet.missing ### Description ``` public SolrQuery::setFacetMissing(bool $flag, string $field_override = ?): SolrQuery ``` Used to indicate that in addition to the Term-based constraints of a facet field, a count of all matching results which have no value for the field should be computed ### Parameters `flag` **`true`** turns this feature on. **`false`** disables it. `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php PDOStatement::setAttribute PDOStatement::setAttribute ========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8, PECL pdo >= 0.2.0) PDOStatement::setAttribute — Set a statement attribute ### Description ``` public PDOStatement::setAttribute(int $attribute, mixed $value): bool ``` Sets an attribute on the statement. Currently, no generic attributes are set but only driver specific: * `PDO::ATTR_CURSOR_NAME` (Firebird and ODBC specific): Set the name of cursor for `UPDATE ... WHERE CURRENT OF`. Note that driver specific attributes *must not* be used with other drivers. ### Parameters `attribute` The attribute to modify. `value` The value to set the `attribute`, might require a specific type depending on the attribute. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [PDO::getAttribute()](pdo.getattribute) - Retrieve a database connection attribute * [PDO::setAttribute()](pdo.setattribute) - Set an attribute * [PDOStatement::getAttribute()](pdostatement.getattribute) - Retrieve a statement attribute php imap_getmailboxes imap\_getmailboxes ================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_getmailboxes — Read the list of mailboxes, returning detailed information on each one ### Description ``` imap_getmailboxes(IMAP\Connection $imap, string $reference, string $pattern): array|false ``` Gets information on the mailboxes. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `reference` `reference` should normally be just the server specification as described in [imap\_open()](function.imap-open) **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `pattern` Specifies where in the mailbox hierarchy to start searching. There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory. ### Return Values Returns an array of objects containing mailbox information. Each object has the attributes `name`, specifying the full name of the mailbox; `delimiter`, which is the hierarchy delimiter for the part of the hierarchy this mailbox is in; and `attributes`. `Attributes` is a bitmask that can be tested against: * **`LATT_NOINFERIORS`** - This mailbox not contains, and may not contain any "children" (there are no mailboxes below this one). Calling [imap\_createmailbox()](function.imap-createmailbox) will not work on this mailbox. * **`LATT_NOSELECT`** - This is only a container, not a mailbox - you cannot open it. * **`LATT_MARKED`** - This mailbox is marked. This means that it may contain new messages since the last time it was checked. Not provided by all IMAP servers. * **`LATT_UNMARKED`** - This mailbox is not marked, does not contain new messages. If either **`MARKED`** or **`UNMARKED`** is provided, you can assume the IMAP server supports this feature for this mailbox. * **`LATT_REFERRAL`** - This container has a referral to a remote mailbox. * **`LATT_HASCHILDREN`** - This mailbox has selectable inferiors. * **`LATT_HASNOCHILDREN`** - This mailbox has no selectable inferiors. The function returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_getmailboxes()** example** ``` <?php $mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)       or die("can't connect: " . imap_last_error()); $list = imap_getmailboxes($mbox, "{imap.example.org}", "*"); if (is_array($list)) {     foreach ($list as $key => $val) {         echo "($key) ";         echo imap_utf7_decode($val->name) . ",";         echo "'" . $val->delimiter . "',";         echo $val->attributes . "<br />\n";     } } else {     echo "imap_getmailboxes failed: " . imap_last_error() . "\n"; } imap_close($mbox); ?> ``` ### See Also * [imap\_getsubscribed()](function.imap-getsubscribed) - List all the subscribed mailboxes php RarEntry::getFileTime RarEntry::getFileTime ===================== (PECL rar >= 0.1) RarEntry::getFileTime — Get entry last modification time ### Description ``` public RarEntry::getFileTime(): string ``` Gets entry last modification time. ### Parameters This function has no parameters. ### Return Values Returns entry last modification time as string in format `YYYY-MM-DD HH:II:SS`, or **`false`** on error. php date_sun_info date\_sun\_info =============== (PHP 5 >= 5.1.2, PHP 7, PHP 8) date\_sun\_info — Returns an array with information about sunset/sunrise and twilight begin/end ### Description ``` date_sun_info(int $timestamp, float $latitude, float $longitude): array ``` ### Parameters `timestamp` Unix timestamp. `latitude` Latitude in degrees. `longitude` Longitude in degrees. ### Return Values Returns array on success or **`false`** on failure. The structure of the array is detailed in the following list: `sunrise` The timestamp of the sunrise (zenith angle = 90°35'). `sunset` The timestamp of the sunset (zenith angle = 90°35'). `transit` The timestamp when the sun is at its zenith, i.e. has reached its topmost point. `civil_twilight_begin` The start of the civil dawn (zenith angle = 96°). It ends at `sunrise`. `civil_twilight_end` The end of the civil dusk (zenith angle = 96°). It starts at `sunset`. `nautical_twilight_begin` The start of the nautical dawn (zenith angle = 102°). It ends at `civil_twilight_begin`. `nautical_twilight_end` The end of the nautical dusk (zenith angle = 102°). It starts at `civil_twilight_end`. `astronomical_twilight_begin` The start of the astronomical dawn (zenith angle = 108°). It ends at `nautical_twilight_begin`. `astronomical_twilight_end` The end of the astronomical dusk (zenith angle = 108°). It starts at `nautical_twilight_end`. The values of the array elements are either UNIX timestamps, **`false`** if the sun is below the respective zenith for the whole day, or **`true`** if the sun is above the respective zenith for the whole day. ### Changelog | Version | Description | | --- | --- | | 7.2.0 | The calculation was fixed with regards to local midnight instead of local noon, which changes the results slightly. | ### Examples **Example #1 A **date\_sun\_info()** example** ``` <?php $sun_info = date_sun_info(strtotime("2006-12-12"), 31.7667, 35.2333); foreach ($sun_info as $key => $val) {     echo "$key: " . date("H:i:s", $val) . "\n"; } ?> ``` The above example will output: ``` sunrise: 05:52:11 sunset: 15:41:21 transit: 10:46:46 civil_twilight_begin: 05:24:08 civil_twilight_end: 16:09:24 nautical_twilight_begin: 04:52:25 nautical_twilight_end: 16:41:06 astronomical_twilight_begin: 04:21:32 astronomical_twilight_end: 17:12:00 ``` **Example #2 Polar night, with some processing** ``` <?php $tz = new \DateTimeZone('America/Anchorage'); $si = date_sun_info(strtotime("2022-12-21"), 70.21, -148.51); foreach ($si as $key => $value) {     echo         match ($value) {             true => 'always',             false => 'never',             default => date_create("@{$value}")->setTimeZone($tz)->format( 'H:i:s T' ),         },         ": {$key}",         "\n"; } ?> ``` The above example will output: ``` never: sunrise never: sunset 12:52:18 AKST: transit 10:53:19 AKST: civil_twilight_begin 14:51:17 AKST: civil_twilight_end 09:01:47 AKST: nautical_twilight_begin 16:42:48 AKST: nautical_twilight_end 07:40:47 AKST: astronomical_twilight_begin 18:03:49 AKST: astronomical_twilight_end ``` **Example #3 Midnight sun (Tromsø, Norway)** ``` <?php $si = date_sun_info(strtotime("2022-06-26"), 69.68, 18.94); print_r($si); ?> ``` The above example will output: ``` Array ( [sunrise] => 1 [sunset] => 1 [transit] => 1656240426 [civil_twilight_begin] => 1 [civil_twilight_end] => 1 [nautical_twilight_begin] => 1 [nautical_twilight_end] => 1 [astronomical_twilight_begin] => 1 [astronomical_twilight_end] => 1 ) ``` **Example #4 Calculating length of day (Kyiv)** ``` <?php $si = date_sun_info(strtotime('2022-08-26'), 50.45, 30.52); $diff = $si['sunset'] - $si['sunrise']; echo "Length of day: ",     floor($diff / 3600), "h ",     floor(($diff % 3600) / 60), "s\n"; ?> ``` The above example will output: ``` Length of day: 13h 56s ```
programming_docs
php bcmod bcmod ===== (PHP 4, PHP 5, PHP 7, PHP 8) bcmod — Get modulus of an arbitrary precision number ### Description ``` bcmod(string $num1, string $num2, ?int $scale = null): string ``` Get the remainder of dividing `num1` by `num2`. Unless `num2` is zero, the result has the same sign as `num1`. ### Parameters `num1` The dividend, as a string. `num2` The divisor, as a string. ### Return Values Returns the modulus as a string, or **`null`** if `num2` is `0`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `scale` is now nullable. | | 7.2.0 | `num1` and `num2` are no longer truncated to integer, so now the behavior of **bcmod()** follows [fmod()](function.fmod) rather than the `%` operator. | | 7.2.0 | The `scale` parameter was added. | ### Examples **Example #1 **bcmod()** example** ``` <?php bcscale(0); echo bcmod( '5',  '3'); //  2 echo bcmod( '5', '-3'); //  2 echo bcmod('-5',  '3'); // -2 echo bcmod('-5', '-3'); // -2 ?> ``` **Example #2 **bcmod()** with decimals** ``` <?php bcscale(1); echo bcmod('5.7', '1.3'); // 0.5 as of PHP 7.2.0; 0 previously ?> ``` ### See Also * [bcdiv()](function.bcdiv) - Divide two arbitrary precision numbers php Yac::set Yac::set ======== (PECL yac >= 1.0.0) Yac::set — Store into cache ### Description ``` public Yac::set(string $keys, mixed $value, int $ttl = 0): bool ``` ``` public Yac::add(array $key_vals): bool ``` Add a item into cache, it the key is already exists, override it. ### Parameters `keys` string key `value` mixed value, All php value type could be stored except [resource](language.types.resource) `ttl` expire time ### Return Values the value self php SQLite3Result::columnName SQLite3Result::columnName ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Result::columnName — Returns the name of the nth column ### Description ``` public SQLite3Result::columnName(int $column): string|false ``` Returns the name of the column specified by the `column`. Note that the name of a result column is the value of the `AS` clause for that column, if there is an `AS` clause. If there is no `AS` clause then the name of the column is unspecified and may change from one release of libsqlite3 to the next. ### Parameters `column` The numeric zero-based index of the column. ### Return Values Returns the string name of the column identified by `column`, or **`false`** if the column does not exist. php Yaf_Config_Simple::count Yaf\_Config\_Simple::count ========================== (Yaf >=1.0.0) Yaf\_Config\_Simple::count — The count purpose ### Description ``` public Yaf_Config_Simple::count(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php The SodiumException class The SodiumException class ========================= Introduction ------------ (PHP 7 >= 7.2.0, PHP 8) Exceptions thrown by the sodium functions. Class synopsis -------------- class **SodiumException** extends [Exception](class.exception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php Imagick::getImageFilename Imagick::getImageFilename ========================= (PECL imagick 2, PECL imagick 3) Imagick::getImageFilename — Returns the filename of a particular image in a sequence ### Description ``` public Imagick::getImageFilename(): string ``` Returns the filename of a particular image in a sequence. ### Parameters This function has no parameters. ### Return Values Returns a string with the filename of the image. ### Errors/Exceptions Throws ImagickException on error. php Gmagick::getreleasedate Gmagick::getreleasedate ======================= (PECL gmagick >= Unknown) Gmagick::getreleasedate — Returns the GraphicsMagick release date as a string ### Description ``` public Gmagick::getreleasedate(): string ``` Returns the GraphicsMagick release date as a string. ### Parameters This function has no parameters. ### Return Values Returns the GraphicsMagick release date as a string. ### Errors/Exceptions Throws an **GmagickException** on error. php SolrQuery::setMltMaxWordLength SolrQuery::setMltMaxWordLength ============================== (PECL solr >= 0.9.2) SolrQuery::setMltMaxWordLength — Sets the maximum word length ### Description ``` public SolrQuery::setMltMaxWordLength(int $maxWordLength): SolrQuery ``` Sets the maximum word length above which words will be ignored. ### Parameters `maxWordLength` The maximum word length above which words will be ignored ### Return Values Returns the current SolrQuery object, if the return value is used. php SimpleXMLIterator::key SimpleXMLIterator::key ====================== (PHP 5, PHP 7, PHP 8) SimpleXMLIterator::key — Return current key ### Description ``` public SimpleXMLIterator::key(): mixed ``` This method gets the XML tag name of the current element. ### Parameters This function has no parameters. ### Return Values Returns the XML tag name of the element referenced by the current [SimpleXMLIterator](class.simplexmliterator) object or **`false`** ### Examples **Example #1 Get the current XML tag key** ``` <?php $xmlIterator = new SimpleXMLIterator('<books><book>PHP basics</book><book>XML basics</book></books>'); echo var_dump($xmlIterator->key()); $xmlIterator->rewind(); // rewind to the first element echo var_dump($xmlIterator->key()); ?> ``` The above example will output: ``` bool(false) string(4) "book" ``` php IntlTimeZone::getID IntlTimeZone::getID =================== intltz\_get\_id =============== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::getID -- intltz\_get\_id — Get timezone ID ### Description Object-oriented style (method): ``` public IntlTimeZone::getID(): string|false ``` Procedural style: ``` intltz_get_id(IntlTimeZone $timezone): string|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php SyncEvent::reset SyncEvent::reset ================ (PECL sync >= 1.0.0) SyncEvent::reset — Resets a manual event ### Description ``` public SyncEvent::reset(): bool ``` Resets a [SyncEvent](class.syncevent) object that has been fired/set. Only valid for manual event objects. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SyncEvent::reset()** example** ``` <?php // In a web application: $event = new SyncEvent("DemoApplication", true); $event->wait(); // In a cron job: $event = new SyncEvent("DemoApplication", true); $event->reset(); /* ... Do some maintenance task(s) ... */ $event->fire(); ?> ``` ### See Also * [SyncEvent::fire()](syncevent.fire) - Fires/sets the event * **SyncEvent::reset()** * [SyncEvent::wait()](syncevent.wait) - Waits for the event to be fired/set php ResourceBundle::getErrorMessage ResourceBundle::getErrorMessage =============================== resourcebundle\_get\_error\_message =================================== (PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0) ResourceBundle::getErrorMessage -- resourcebundle\_get\_error\_message — Get bundle's last error message ### Description Object-oriented style ``` public ResourceBundle::getErrorMessage(): string ``` Procedural style ``` resourcebundle_get_error_message(ResourceBundle $bundle): string ``` Get error message from the last function performed by the bundle object. ### Parameters `bundle` [ResourceBundle](class.resourcebundle) object. ### Return Values Returns error message from last bundle object's call. ### Examples **Example #1 **resourcebundle\_get\_error\_message()** example** ``` <?php $r = resourcebundle_create( 'es', "/usr/share/data/myapp"); echo $r['somestring']; if(intl_is_failure(resourcebundle_get_error_code($r))) {     report_error("Bundle error: ".resourcebundle_get_error_message($r)); } ?> ``` **Example #2 OO example** ``` <?php $r = new ResourceBundle( 'es', "/usr/share/data/myapp"); echo $r['somestring']; if(intl_is_failure(ResourceBundle::getErrorCode($r))) {     report_error("Bundle error: ".ResourceBundle::getErrorMessage($r)); } ?> ``` ### See Also * [resourcebundle\_get\_error\_code()](resourcebundle.geterrorcode) - Get bundle's last error code * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure php imagesetinterpolation imagesetinterpolation ===================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) imagesetinterpolation — Set the interpolation method ### Description ``` imagesetinterpolation(GdImage $image, int $method = IMG_BILINEAR_FIXED): bool ``` Sets the interpolation method, setting an interpolation method affects the rendering of various functions in GD, such as the [imagerotate()](function.imagerotate) function. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `method` The interpolation method, which can be one of the following: * **`IMG_BELL`**: Bell filter. * **`IMG_BESSEL`**: Bessel filter. * **`IMG_BICUBIC`**: Bicubic interpolation. * **`IMG_BICUBIC_FIXED`**: Fixed point implementation of the bicubic interpolation. * **`IMG_BILINEAR_FIXED`**: Fixed point implementation of the bilinear interpolation (`default (also on image creation)`). * **`IMG_BLACKMAN`**: Blackman window function. * **`IMG_BOX`**: Box blur filter. * **`IMG_BSPLINE`**: Spline interpolation. * **`IMG_CATMULLROM`**: Cubic Hermite spline interpolation. * **`IMG_GAUSSIAN`**: Gaussian function. * **`IMG_GENERALIZED_CUBIC`**: Generalized cubic spline fractal interpolation. * **`IMG_HERMITE`**: Hermite interpolation. * **`IMG_HAMMING`**: Hamming filter. * **`IMG_HANNING`**: Hanning filter. * **`IMG_MITCHELL`**: Mitchell filter. * **`IMG_POWER`**: Power interpolation. * **`IMG_QUADRATIC`**: Inverse quadratic interpolation. * **`IMG_SINC`**: Sinc function. * **`IMG_NEAREST_NEIGHBOUR`**: Nearest neighbour interpolation. * **`IMG_WEIGHTED4`**: Weighting filter. * **`IMG_TRIANGLE`**: Triangle interpolation. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagesetinterpolation()** example** ``` <?php // Load an image $im = imagecreate(500, 500); // By default interpolation is IMG_BILINEAR_FIXED, switch  // to use the 'Mitchell' filter: imagesetinterpolation($im, IMG_MITCHELL); // Continue to work with $im ... ?> ``` ### Notes Changing the interpolation method affects the following functions when rendering: * [imageaffine()](function.imageaffine) * [imagerotate()](function.imagerotate) ### See Also * [imagegetinterpolation()](function.imagegetinterpolation) - Get the interpolation method php gzencode gzencode ======== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gzencode — Create a gzip compressed string ### Description ``` gzencode(string $data, int $level = -1, int $encoding = ZLIB_ENCODING_GZIP): string|false ``` This function returns a compressed version of the input `data` compatible with the output of the **gzip** program. For more information on the GZIP file format, see the document: [» GZIP file format specification version 4.3](http://www.faqs.org/rfcs/rfc1952) (RFC 1952). ### Parameters `data` The data to encode. `level` The level of compression. Can be given as 0 for no compression up to 9 for maximum compression. If not given, the default compression level will be the default compression level of the zlib library. `encoding` The encoding mode. Can be **`FORCE_GZIP`** (the default) or **`FORCE_DEFLATE`**. **`FORCE_DEFLATE`** generates RFC 1950 compliant output, consisting of a zlib header, the deflated data, and an Adler checksum. ### Return Values The encoded string, or **`false`** if an error occurred. ### Examples The resulting data contains the appropriate headers and data structure to make a standard .gz file, e.g.: **Example #1 Creating a gzip file** ``` <?php $data = file_get_contents("bigfile.txt"); $gzdata = gzencode($data, 9); file_put_contents("bigfile.txt.gz", $gzdata); ?> ``` ### See Also * [gzdecode()](function.gzdecode) - Decodes a gzip compressed string * [gzdeflate()](function.gzdeflate) - Deflate a string * [gzinflate()](function.gzinflate) - Inflate a deflated string * [gzuncompress()](function.gzuncompress) - Uncompress a compressed string * [gzcompress()](function.gzcompress) - Compress a string * [» ZLIB Compressed Data Format Specification (RFC 1950)](http://www.faqs.org/rfcs/rfc1950) php function_exists function\_exists ================ (PHP 4, PHP 5, PHP 7, PHP 8) function\_exists — Return **`true`** if the given function has been defined ### Description ``` function_exists(string $function): bool ``` Checks the list of defined functions, both built-in (internal) and user-defined, for `function`. ### Parameters `function` The function name, as a string. ### Return Values Returns **`true`** if `function` exists and is a function, **`false`** otherwise. > > **Note**: > > > This function will return **`false`** for constructs, such as [include\_once](function.include-once) and [echo](function.echo). > > ### Examples **Example #1 **function\_exists()** example** ``` <?php if (function_exists('imap_open')) {     echo "IMAP functions are available.<br />\n"; } else {     echo "IMAP functions are not available.<br />\n"; } ?> ``` ### Notes > > **Note**: > > > A function name may exist even if the function itself is unusable due to configuration or compiling options (with the [image](https://www.php.net/manual/en/ref.image.php) functions being an example). > > ### See Also * [method\_exists()](function.method-exists) - Checks if the class method exists * [is\_callable()](function.is-callable) - Verify that a value can be called as a function from the current scope. * [get\_defined\_functions()](function.get-defined-functions) - Returns an array of all defined functions * [class\_exists()](function.class-exists) - Checks if the class has been defined * [extension\_loaded()](function.extension-loaded) - Find out whether an extension is loaded php svn_export svn\_export =========== (PECL svn >= 0.3.0) svn\_export — Export the contents of a SVN directory ### Description ``` svn_export( string $frompath, string $topath, bool $working_copy = true, int $revision_no = -1 ): bool ``` Export the contents of either a working copy or repository into a 'clean' directory. ### Parameters `frompath` The path to the current repository. `topath` The path to the new repository. `working_copy` If **`true`**, it will export uncommitted files from the working copy. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **svn\_export()** example** ``` <?php $working_dir     = '../'; $new_working_dir = '/home/user/devel/foo/trunk'; svn_export($working_dir, $new_working_dir); ?> ``` ### See Also * [svn\_import()](function.svn-import) - Imports an unversioned path into a repository php mhash_get_block_size mhash\_get\_block\_size ======================= (PHP 4, PHP 5, PHP 7, PHP 8) mhash\_get\_block\_size — Gets the block size of the specified hash **Warning**This function has been *DEPRECATED* as of PHP 8.1.0. Relying on this function is highly discouraged. ### Description ``` mhash_get_block_size(int $algo): int|false ``` Gets the size of a block of the specified `algo`. ### Parameters `algo` The hash ID. One of the **`MHASH_hashname`** constants. ### Return Values Returns the size in bytes or **`false`**, if the `algo` does not exist. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This function has been deprecated. Use the [`hash_*()` functions](https://www.php.net/manual/en/ref.hash.php) instead. | ### Examples **Example #1 **mhash\_get\_block\_size()** Example** ``` <?php echo mhash_get_block_size(MHASH_MD5); // 16 ?> ``` php Memcached::deleteMultiByKey Memcached::deleteMultiByKey =========================== (PECL memcached >= 2.0.0) Memcached::deleteMultiByKey — Delete multiple items from a specific server ### Description ``` public Memcached::deleteMultiByKey(string $server_key, array $keys, int $time = 0): bool ``` **Memcached::deleteMultiByKey()** is functionally equivalent to [Memcached::deleteMulti()](memcached.deletemulti), except that the free-form `server_key` can be used to map the `keys` to a specific server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `keys` The keys to be deleted. `time` The amount of time the server will wait to delete the items. > **Note**: As of memcached 1.3.0 (released 2009) this feature is no longer supported. Passing a non-zero `time` will cause the deletion to fail. [Memcached::getResultCode()](memcached.getresultcode) will return **`MEMCACHED_INVALID_ARGUMENTS`**. > > ### Return Values Returns an array indexed by `keys`. Each element is **`true`** if the corresponding key was deleted, or one of the **`Memcached::RES_*`** constants if the corresponding deletion failed. The [Memcached::getResultCode()](memcached.getresultcode) will return the result code for the last executed delete operation, that is, the delete operation for the last element of `keys`. ### See Also * [Memcached::delete()](memcached.delete) - Delete an item * [Memcached::deleteByKey()](memcached.deletebykey) - Delete an item from a specific server * [Memcached::deleteMulti()](memcached.deletemulti) - Delete multiple items
programming_docs
php getenv getenv ====== (PHP 4, PHP 5, PHP 7, PHP 8) getenv — Gets the value of an environment variable ### Description ``` getenv(string $varname, bool $local_only = false): string|false ``` ``` getenv(): array ``` Gets the value of an environment variable. You can see a list of all the environmental variables by using [phpinfo()](function.phpinfo). Many of these variables are listed within [» RFC 3875](http://www.faqs.org/rfcs/rfc3875), specifically section 4.1, "Request Meta-Variables". ### Parameters `varname` The variable name. `local_only` Set to true to only return local environment variables (set by the operating system or putenv). ### Return Values Returns the value of the environment variable `varname`, or **`false`** if the environment variable `varname` does not exist. If `varname` is omitted, all environment variables are returned as associative array. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | The `varname` can now be omitted to retrieve an associative array of all environment variables. | | 7.0.9 | The `local_only` parameter has been added. | ### Examples **Example #1 **getenv()** Example** ``` <?php // Example use of getenv() $ip = getenv('REMOTE_ADDR'); // Or simply use a Superglobal ($_SERVER or $_ENV) $ip = $_SERVER['REMOTE_ADDR']; // Safely get the value of an environment variable, ignoring whether  // or not it was set by a SAPI or has been changed with putenv $ip = getenv('REMOTE_ADDR', true) ?: getenv('REMOTE_ADDR') ?> ``` ### Notes **Warning** If PHP is running in a SAPI such as Fast CGI, this function will always return the value of an environment variable set by the SAPI, even if [putenv()](function.putenv) has been used to set a local environment variable of the same name. Use the `local_only` parameter to return the value of locally-set environment variables. ### See Also * [putenv()](function.putenv) - Sets the value of an environment variable * [apache\_getenv()](function.apache-getenv) - Get an Apache subprocess\_env variable * [Superglobals](language.variables.superglobals) php ldap_mod_del_ext ldap\_mod\_del\_ext =================== (PHP 7 >= 7.3.0, PHP 8) ldap\_mod\_del\_ext — Delete attribute values from current attributes ### Description ``` ldap_mod_del_ext( LDAP\Connection $ldap, string $dn, array $entry, ?array $controls = null ): LDAP\Result|false ``` Does the same thing as [ldap\_mod\_del()](function.ldap-mod-del) but returns an [LDAP\Result](class.ldap-result) instance to be parsed with [ldap\_parse\_result()](function.ldap-parse-result). ### Parameters See [ldap\_mod\_del()](function.ldap-mod-del) ### Return Values Returns an [LDAP\Result](class.ldap-result) instance, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | Returns an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### See Also * [ldap\_mod\_del()](function.ldap-mod-del) - Delete attribute values from current attributes * [ldap\_parse\_result()](function.ldap-parse-result) - Extract information from result php Imagick::getImageSize Imagick::getImageSize ===================== (PECL imagick 2, PECL imagick 3) Imagick::getImageSize — Returns the image length in bytes **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::getImageSize(): int ``` Returns the image length in bytes. Deprecated in favour of [Imagick::getImageLength()](imagick.getimagelength) ### Parameters This function has no parameters. ### Return Values Returns an int containing the current image size. php The SQLite3Result class The SQLite3Result class ======================= Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) A class that handles result sets for the SQLite 3 extension. Class synopsis -------------- class **SQLite3Result** { /\* Methods \*/ private [\_\_construct](sqlite3result.construct)() ``` public columnName(int $column): string|false ``` ``` public columnType(int $column): int|false ``` ``` public fetchArray(int $mode = SQLITE3_BOTH): array|false ``` ``` public finalize(): bool ``` ``` public numColumns(): int ``` ``` public reset(): bool ``` } Table of Contents ----------------- * [SQLite3Result::columnName](sqlite3result.columnname) — Returns the name of the nth column * [SQLite3Result::columnType](sqlite3result.columntype) — Returns the type of the nth column * [SQLite3Result::\_\_construct](sqlite3result.construct) — Constructs an SQLite3Result * [SQLite3Result::fetchArray](sqlite3result.fetcharray) — Fetches a result row as an associative or numerically indexed array or both * [SQLite3Result::finalize](sqlite3result.finalize) — Closes the result set * [SQLite3Result::numColumns](sqlite3result.numcolumns) — Returns the number of columns in the result set * [SQLite3Result::reset](sqlite3result.reset) — Resets the result set back to the first row php ibase_modify_user ibase\_modify\_user =================== (PHP 5, PHP 7 < 7.4.0) ibase\_modify\_user — Modify a user to a security database ### Description ``` ibase_modify_user( resource $service_handle, string $user_name, string $password, string $first_name = ?, string $middle_name = ?, string $last_name = ? ): bool ``` ### Parameters `service_handle` The handle on the database server service. `user_name` The login name of the database user to modify. `password` The user's new password. `first_name` The user's new first name. `middle_name` The user's new middle name. `last_name` The user's new last name. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [ibase\_add\_user()](function.ibase-add-user) - Add a user to a security database * [ibase\_delete\_user()](function.ibase-delete-user) - Delete a user from a security database php SolrQuery::getTermsMaxCount SolrQuery::getTermsMaxCount =========================== (PECL solr >= 0.9.2) SolrQuery::getTermsMaxCount — Returns the maximum document frequency ### Description ``` public SolrQuery::getTermsMaxCount(): int ``` Returns the maximum document frequency ### Parameters This function has no parameters. ### Return Values Returns an integer on success and **`null`** if not set. php Throwable::getLine Throwable::getLine ================== (PHP 7, PHP 8) Throwable::getLine — Gets the line on which the object was instantiated ### Description ``` public Throwable::getLine(): int ``` Returns the line number where the thrown object was instantiated. ### Parameters This function has no parameters. ### Return Values Returns the line number where the thrown object was instantiated. ### See Also * [Exception::getLine()](exception.getline) - Gets the line in which the exception was created php OAuthProvider::is2LeggedEndpoint OAuthProvider::is2LeggedEndpoint ================================ (PECL OAuth >= 1.0.0) OAuthProvider::is2LeggedEndpoint — is2LeggedEndpoint ### Description ``` public OAuthProvider::is2LeggedEndpoint(mixed $params_array): void ``` The 2-legged flow, or request signing. It does not require a token. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `params_array` ### Return Values An [OAuthProvider](class.oauthprovider) object. ### Examples **Example #1 **OAuthProvider::is2LeggedEndpoint()** example** ``` <?php $provider = new OAuthProvider(); $provider->is2LeggedEndpoint(true); ?> ``` ### See Also * [OAuthProvider::\_\_construct()](oauthprovider.construct) - Constructs a new OAuthProvider object php curl_multi_setopt curl\_multi\_setopt =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) curl\_multi\_setopt — Set an option for the cURL multi handle ### Description ``` curl_multi_setopt(CurlMultiHandle $multi_handle, int $option, mixed $value): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `multi_handle` `option` One of the **`CURLMOPT_*`** constants. `value` The value to be set on `option`. `value` should be an int for the following values of the `option` parameter: | Option | Set `value` to | | --- | --- | | **`CURLMOPT_PIPELINING`** | Pass 1 to enable or 0 to disable. Enabling pipelining on a multi handle will make it attempt to perform HTTP Pipelining as far as possible for transfers using this handle. This means that if you add a second request that can use an already existing connection, the second request will be "piped" on the same connection. As of cURL 7.43.0, the value is a bitmask, and you can also pass 2 to try to multiplex the new transfer over an existing HTTP/2 connection if possible. Passing 3 instructs cURL to ask for pipelining and multiplexing independently of each other. As of cURL 7.62.0, setting the pipelining bit has no effect. Instead of integer literals, you can also use the CURLPIPE\_\* constants if available. | | **`CURLMOPT_MAXCONNECTS`** | Pass a number that will be used as the maximum amount of simultaneously open connections that libcurl may cache. By default the size will be enlarged to fit four times the number of handles added via [curl\_multi\_add\_handle()](function.curl-multi-add-handle). When the cache is full, curl closes the oldest one in the cache to prevent the number of open connections from increasing. | | **`CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE`** | Pass a number that specifies the chunk length threshold for pipelining in bytes. | | **`CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE`** | Pass a number that specifies the size threshold for pipelining penalty in bytes. | | **`CURLMOPT_MAX_HOST_CONNECTIONS`** | Pass a number that specifies the maximum number of connections to a single host. | | **`CURLMOPT_MAX_PIPELINE_LENGTH`** | Pass a number that specifies the maximum number of requests in a pipeline. | | **`CURLMOPT_MAX_TOTAL_CONNECTIONS`** | Pass a number that specifies the maximum number of simultaneously open connections. | | **`CURLMOPT_PUSHFUNCTION`** | Pass a [callable](language.types.callable) that will be registered to handle server pushes and should have the following signature: ``` pushfunction(resource $parent_ch, resource $pushed_ch, array $headers): int ``` `parent_ch` The parent cURL handle (the request the client made). `pushed_ch` A new cURL handle for the pushed request. `headers` The push promise headers. The push function is supposed to return either **`CURL_PUSH_OK`** if it can handle the push, or **`CURL_PUSH_DENY`** to reject it. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `multi_handle` expects a [CurlMultiHandle](class.curlmultihandle) instance now; previously, a resource was expected. | | 7.1.0 | Introduced **`CURLMOPT_PUSHFUNCTION`**. | | 7.0.7 | Introduced **`CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE`**, **`CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE`**, **`CURLMOPT_MAX_HOST_CONNECTIONS`**, **`CURLMOPT_MAX_PIPELINE_LENGTH`** and **`CURLMOPT_MAX_TOTAL_CONNECTIONS`**. | php None Class Abstraction ----------------- PHP has abstract classes and methods. Classes defined as abstract cannot be instantiated, and any class that contains at least one abstract method must also be abstract. Methods defined as abstract simply declare the method's signature; they cannot define the implementation. When inheriting from an abstract class, all methods marked abstract in the parent's class declaration must be defined by the child class, and follow the usual [inheritance](language.oop5.inheritance) and [signature compatibility](language.oop5.basic#language.oop.lsp) rules. **Example #1 Abstract class example** ``` <?php abstract class AbstractClass {     // Force Extending class to define this method     abstract protected function getValue();     abstract protected function prefixValue($prefix);     // Common method     public function printOut() {         print $this->getValue() . "\n";     } } class ConcreteClass1 extends AbstractClass {     protected function getValue() {         return "ConcreteClass1";     }     public function prefixValue($prefix) {         return "{$prefix}ConcreteClass1";     } } class ConcreteClass2 extends AbstractClass {     public function getValue() {         return "ConcreteClass2";     }     public function prefixValue($prefix) {         return "{$prefix}ConcreteClass2";     } } $class1 = new ConcreteClass1; $class1->printOut(); echo $class1->prefixValue('FOO_') ."\n"; $class2 = new ConcreteClass2; $class2->printOut(); echo $class2->prefixValue('FOO_') ."\n"; ?> ``` The above example will output: ``` ConcreteClass1 FOO_ConcreteClass1 ConcreteClass2 FOO_ConcreteClass2 ``` **Example #2 Abstract class example** ``` <?php abstract class AbstractClass {     // Our abstract method only needs to define the required arguments     abstract protected function prefixName($name); } class ConcreteClass extends AbstractClass {     // Our child class may define optional arguments not in the parent's signature     public function prefixName($name, $separator = ".") {         if ($name == "Pacman") {             $prefix = "Mr";         } elseif ($name == "Pacwoman") {             $prefix = "Mrs";         } else {             $prefix = "";         }         return "{$prefix}{$separator} {$name}";     } } $class = new ConcreteClass; echo $class->prefixName("Pacman"), "\n"; echo $class->prefixName("Pacwoman"), "\n"; ?> ``` The above example will output: ``` Mr. Pacman Mrs. Pacwoman ``` php printf printf ====== (PHP 4, PHP 5, PHP 7, PHP 8) printf — Output a formatted string ### Description ``` printf(string $format, mixed ...$values): int ``` Produces output according to `format`. ### Parameters `format` The format string is composed of zero or more directives: ordinary characters (excluding `%`) that are copied directly to the result and *conversion specifications*, each of which results in fetching its own parameter. A conversion specification follows this prototype: `%[argnum$][flags][width][.precision]specifier`. ##### Argnum An integer followed by a dollar sign `$`, to specify which number argument to treat in the conversion. **Flags**| Flag | Description | | --- | --- | | `-` | Left-justify within the given field width; Right justification is the default | | `+` | Prefix positive numbers with a plus sign `+`; Default only negative are prefixed with a negative sign. | | (space) | Pads the result with spaces. This is the default. | | `0` | Only left-pads numbers with zeros. With `s` specifiers this can also right-pad with zeros. | | `'`(char) | Pads the result with the character (char). | ##### Width An integer that says how many characters (minimum) this conversion should result in. ##### Precision A period `.` followed by an integer who's meaning depends on the specifier: * For `e`, `E`, `f` and `F` specifiers: this is the number of digits to be printed after the decimal point (by default, this is 6). * For `g`, `G`, `h` and `H` specifiers: this is the maximum number of significant digits to be printed. * For `s` specifier: it acts as a cutoff point, setting a maximum character limit to the string. > **Note**: If the period is specified without an explicit value for precision, 0 is assumed. > > > **Note**: Attempting to use a position specifier greater than **`PHP_INT_MAX`** will generate warnings. > > **Specifiers**| Specifier | Description | | --- | --- | | `%` | A literal percent character. No argument is required. | | `b` | The argument is treated as an integer and presented as a binary number. | | `c` | The argument is treated as an integer and presented as the character with that ASCII. | | `d` | The argument is treated as an integer and presented as a (signed) decimal number. | | `e` | The argument is treated as scientific notation (e.g. 1.2e+2). | | `E` | Like the `e` specifier but uses uppercase letter (e.g. 1.2E+2). | | `f` | The argument is treated as a float and presented as a floating-point number (locale aware). | | `F` | The argument is treated as a float and presented as a floating-point number (non-locale aware). | | `g` | General format. Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: If P > X ≥ −4, the conversion is with style f and precision P − (X + 1). Otherwise, the conversion is with style e and precision P − 1. | | `G` | Like the `g` specifier but uses `E` and `f`. | | `h` | Like the `g` specifier but uses `F`. Available as of PHP 8.0.0. | | `H` | Like the `g` specifier but uses `E` and `F`. Available as of PHP 8.0.0. | | `o` | The argument is treated as an integer and presented as an octal number. | | `s` | The argument is treated and presented as a string. | | `u` | The argument is treated as an integer and presented as an unsigned decimal number. | | `x` | The argument is treated as an integer and presented as a hexadecimal number (with lowercase letters). | | `X` | The argument is treated as an integer and presented as a hexadecimal number (with uppercase letters). | **Warning** The `c` type specifier ignores padding and width **Warning** Attempting to use a combination of the string and width specifiers with character sets that require more than one byte per character may result in unexpected results Variables will be co-erced to a suitable type for the specifier: **Type Handling**| Type | Specifiers | | --- | --- | | string | `s` | | int | `d`, `u`, `c`, `o`, `x`, `X`, `b` | | float | `e`, `E`, `f`, `F`, `g`, `G`, `h`, `H` | `values` ### Return Values Returns the length of the outputted string. ### Examples **Example #1 **printf()**: various examples** ``` <?php $n =  43951789; $u = -43951789; $c = 65; // ASCII 65 is 'A' // notice the double %%, this prints a literal '%' character printf("%%b = '%b'\n", $n); // binary representation printf("%%c = '%c'\n", $c); // print the ascii character, same as chr() function printf("%%d = '%d'\n", $n); // standard integer representation printf("%%e = '%e'\n", $n); // scientific notation printf("%%u = '%u'\n", $n); // unsigned integer representation of a positive integer printf("%%u = '%u'\n", $u); // unsigned integer representation of a negative integer printf("%%f = '%f'\n", $n); // floating point representation printf("%%o = '%o'\n", $n); // octal representation printf("%%s = '%s'\n", $n); // string representation printf("%%x = '%x'\n", $n); // hexadecimal representation (lower-case) printf("%%X = '%X'\n", $n); // hexadecimal representation (upper-case) printf("%%+d = '%+d'\n", $n); // sign specifier on a positive integer printf("%%+d = '%+d'\n", $u); // sign specifier on a negative integer ?> ``` The above example will output: ``` %b = '10100111101010011010101101' %c = 'A' %d = '43951789' %e = '4.39518e+7' %u = '43951789' %u = '4251015507' %f = '43951789.000000' %o = '247523255' %s = '43951789' %x = '29ea6ad' %X = '29EA6AD' %+d = '+43951789' %+d = '-43951789' ``` **Example #2 **printf()**: string specifiers** ``` <?php $s = 'monkey'; $t = 'many monkeys'; printf("[%s]\n",      $s); // standard string output printf("[%10s]\n",    $s); // right-justification with spaces printf("[%-10s]\n",   $s); // left-justification with spaces printf("[%010s]\n",   $s); // zero-padding works on strings too printf("[%'#10s]\n",  $s); // use the custom padding character '#' printf("[%10.9s]\n",  $t); // right-justification but with a cutoff of 8 characters printf("[%-10.9s]\n", $t); // left-justification but with a cutoff of 8 characters ?> ``` The above example will output: ``` [monkey] [ monkey] [monkey ] [0000monkey] [####monkey] [ many monk] [many monk ] ``` ### See Also * [print](function.print) - Output a string * [sprintf()](function.sprintf) - Return a formatted string * [fprintf()](function.fprintf) - Write a formatted string to a stream * [vprintf()](function.vprintf) - Output a formatted string * [vsprintf()](function.vsprintf) - Return a formatted string * [vfprintf()](function.vfprintf) - Write a formatted string to a stream * [sscanf()](function.sscanf) - Parses input from a string according to a format * [fscanf()](function.fscanf) - Parses input from a file according to a format * [number\_format()](function.number-format) - Format a number with grouped thousands * [date()](function.date) - Format a Unix timestamp * [flush()](function.flush) - Flush system output buffer
programming_docs
php SplFileObject::fscanf SplFileObject::fscanf ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplFileObject::fscanf — Parses input from file according to a format ### Description ``` public SplFileObject::fscanf(string $format, mixed &...$vars): array|int|null ``` Reads a line from the file and interprets it according to the specified `format`. Any whitespace in the `format` string matches any whitespace in the line from the file. This means that even a tab (`\t`) in the format string can match a single space character in the input stream. ### Parameters `format` The interpreted format for `string`, which is described in the documentation for [sprintf()](function.sprintf) with following differences: * Function is not locale-aware. * `F`, `g`, `G` and `b` are not supported. * `D` stands for decimal number. * `i` stands for integer with base detection. * `n` stands for number of characters processed so far. * `s` stops reading at any whitespace character. * `*` instead of `argnum$` suppresses the assignment of this conversion specification. `vars` The optional assigned values. ### Return Values If only one parameter is passed to this method, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference. ### Examples **Example #1 **SplFileObject::fscanf()** example** ``` <?php $file = new SplFileObject("misc.txt"); while ($userinfo = $file->fscanf("%s %s %s")) {     list ($name, $profession, $countrycode) = $userinfo;     // Do something with $name $profession $countrycode } ?> ``` Contents of users.txt ``` javier argonaut pe hiroshi sculptor jp robert slacker us luigi florist it ``` ### See Also * [fscanf()](function.fscanf) - Parses input from a file according to a format * [sscanf()](function.sscanf) - Parses input from a string according to a format * [printf()](function.printf) - Output a formatted string * [sprintf()](function.sprintf) - Return a formatted string php eio_fallocate eio\_fallocate ============== (PECL eio >= 0.0.1dev) eio\_fallocate — Allows the caller to directly manipulate the allocated disk space for a file ### Description ``` eio_fallocate( mixed $fd, int $mode, int $offset, int $length, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_fallocate()** allows the caller to directly manipulate the allocated disk space for the file specified by `fd` file descriptor for the byte range starting at `offset` and continuing for `length` bytes. > > **Note**: **File should be opened for writing** > > > > **`EIO_O_CREAT`** should be logically *OR*'d with **`EIO_O_WRONLY`**, or **`EIO_O_RDWR`** > > ### Parameters `fd` Stream, Socket resource, or numeric file descriptor, e.g. returned by [eio\_open()](function.eio-open). `mode` Currently only one flag is supported for mode: **`EIO_FALLOC_FL_KEEP_SIZE`** (the same as POSIX constant **`FALLOC_FL_KEEP_SIZE`**). `offset` Specifies start of the byte range. `length` Specifies length the byte range. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_fallocate()** returns request resource on success, or **`false`** on failure. php SplFileInfo::getPath SplFileInfo::getPath ==================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getPath — Gets the path without filename ### Description ``` public SplFileInfo::getPath(): string ``` Returns the path to the file, omitting the filename and any trailing slash. ### Parameters This function has no parameters. ### Return Values Returns the path to the file. ### Examples **Example #1 **SplFileInfo::getPath()** example** ``` <?php $info = new SplFileInfo('/usr/bin/php'); var_dump($info->getPath()); $info = new SplFileInfo('/usr/'); var_dump($info->getPath());?> ``` The above example will output something similar to: ``` string(8) "/usr/bin" string(4) "/usr" ``` ### See Also * [SplFileInfo::getRealPath()](splfileinfo.getrealpath) - Gets absolute path to file * [SplFileInfo::getFilename()](splfileinfo.getfilename) - Gets the filename * [SplFileInfo::getPathInfo()](splfileinfo.getpathinfo) - Gets an SplFileInfo object for the path php ZipArchive::setArchiveComment ZipArchive::setArchiveComment ============================= (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.4.0) ZipArchive::setArchiveComment — Set the comment of a ZIP archive ### Description ``` public ZipArchive::setArchiveComment(string $comment): bool ``` Set the comment of a ZIP archive. ### Parameters `comment` The contents of the comment. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Create an archive and set a comment** ``` <?php $zip = new ZipArchive; $res = $zip->open('test.zip', ZipArchive::CREATE); if ($res === TRUE) {     $zip->addFromString('test.txt', 'file content goes here');     $zip->setArchiveComment('new archive comment');     $zip->close();     echo 'ok'; } else {     echo 'failed'; } ?> ``` php pg_end_copy pg\_end\_copy ============= (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) pg\_end\_copy — Sync with PostgreSQL backend ### Description ``` pg_end_copy(?PgSql\Connection $connection = null): bool ``` **pg\_end\_copy()** syncs the PostgreSQL frontend (usually a web server process) with the PostgreSQL server after doing a copy operation performed by [pg\_put\_line()](function.pg-put-line). **pg\_end\_copy()** must be issued, otherwise the PostgreSQL server may get out of sync with the frontend and will report an error. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is **`null`**, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `connection` is now nullable. | ### Examples **Example #1 **pg\_end\_copy()** example** ``` <?php    $conn = pg_pconnect("dbname=foo");   pg_query($conn, "create table bar (a int4, b char(16), d float8)");   pg_query($conn, "copy bar from stdin");   pg_put_line($conn, "3\thello world\t4.5\n");   pg_put_line($conn, "4\tgoodbye world\t7.11\n");   pg_put_line($conn, "\\.\n");   pg_end_copy($conn); ?> ``` ### See Also * [pg\_put\_line()](function.pg-put-line) - Send a NULL-terminated string to PostgreSQL backend php uopz_get_static uopz\_get\_static ================= (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_get\_static — Gets the static variables from function or method scope ### Description ``` uopz_get_static(string $class, string $function): array ``` ``` uopz_get_static(string $function): array ``` Gets the static variables from function or method scope. ### Parameters `class` The name of the class. `function` The name of the function or method. ### Return Values Returns an associative array of variable names mapped to their current values on success, or **`null`** if the function or method does not exist. ### Examples **Example #1 Basic **uopz\_get\_static()** Usage** ``` <?php function foo() {     static $bar = 'baz'; } var_dump(uopz_get_static('foo')); ?> ``` The above example will output: ``` array(1) { ["bar"]=> string(3) "baz" } ``` ### See Also * [uopz\_set\_static()](function.uopz-set-static) - Sets the static variables in function or method scope php The SplObjectStorage class The SplObjectStorage class ========================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The SplObjectStorage class provides a map from objects to data or, by ignoring data, an object set. This dual purpose can be useful in many cases involving the need to uniquely identify objects. Class synopsis -------------- class **SplObjectStorage** implements [Countable](class.countable), [Iterator](class.iterator), [Serializable](class.serializable), [ArrayAccess](class.arrayaccess) { /\* Methods \*/ ``` public addAll(SplObjectStorage $storage): int ``` ``` public attach(object $object, mixed $info = null): void ``` ``` public contains(object $object): bool ``` ``` public count(int $mode = COUNT_NORMAL): int ``` ``` public current(): object ``` ``` public detach(object $object): void ``` ``` public getHash(object $object): string ``` ``` public getInfo(): mixed ``` ``` public key(): int ``` ``` public next(): void ``` ``` public offsetExists(object $object): bool ``` ``` public offsetGet(object $object): mixed ``` ``` public offsetSet(object $object, mixed $info = null): void ``` ``` public offsetUnset(object $object): void ``` ``` public removeAll(SplObjectStorage $storage): int ``` ``` public removeAllExcept(SplObjectStorage $storage): int ``` ``` public rewind(): void ``` ``` public serialize(): string ``` ``` public setInfo(mixed $info): void ``` ``` public unserialize(string $data): void ``` ``` public valid(): bool ``` } Examples -------- **Example #1 **SplObjectStorage** as a set** ``` <?php // As an object set $s = new SplObjectStorage(); $o1 = new StdClass; $o2 = new StdClass; $o3 = new StdClass; $s->attach($o1); $s->attach($o2); var_dump($s->contains($o1)); var_dump($s->contains($o2)); var_dump($s->contains($o3)); $s->detach($o2); var_dump($s->contains($o1)); var_dump($s->contains($o2)); var_dump($s->contains($o3)); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(true) bool(false) bool(false) ``` **Example #2 **SplObjectStorage** as a map** ``` <?php // As a map from objects to data $s = new SplObjectStorage(); $o1 = new StdClass; $o2 = new StdClass; $o3 = new StdClass; $s[$o1] = "data for object 1"; $s[$o2] = array(1,2,3); if (isset($s[$o2])) {     var_dump($s[$o2]); } ?> ``` The above example will output: ``` array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ``` Table of Contents ----------------- * [SplObjectStorage::addAll](splobjectstorage.addall) — Adds all objects from another storage * [SplObjectStorage::attach](splobjectstorage.attach) — Adds an object in the storage * [SplObjectStorage::contains](splobjectstorage.contains) — Checks if the storage contains a specific object * [SplObjectStorage::count](splobjectstorage.count) — Returns the number of objects in the storage * [SplObjectStorage::current](splobjectstorage.current) — Returns the current storage entry * [SplObjectStorage::detach](splobjectstorage.detach) — Removes an object from the storage * [SplObjectStorage::getHash](splobjectstorage.gethash) — Calculate a unique identifier for the contained objects * [SplObjectStorage::getInfo](splobjectstorage.getinfo) — Returns the data associated with the current iterator entry * [SplObjectStorage::key](splobjectstorage.key) — Returns the index at which the iterator currently is * [SplObjectStorage::next](splobjectstorage.next) — Move to the next entry * [SplObjectStorage::offsetExists](splobjectstorage.offsetexists) — Checks whether an object exists in the storage * [SplObjectStorage::offsetGet](splobjectstorage.offsetget) — Returns the data associated with an object * [SplObjectStorage::offsetSet](splobjectstorage.offsetset) — Associates data to an object in the storage * [SplObjectStorage::offsetUnset](splobjectstorage.offsetunset) — Removes an object from the storage * [SplObjectStorage::removeAll](splobjectstorage.removeall) — Removes objects contained in another storage from the current storage * [SplObjectStorage::removeAllExcept](splobjectstorage.removeallexcept) — Removes all objects except for those contained in another storage from the current storage * [SplObjectStorage::rewind](splobjectstorage.rewind) — Rewind the iterator to the first storage element * [SplObjectStorage::serialize](splobjectstorage.serialize) — Serializes the storage * [SplObjectStorage::setInfo](splobjectstorage.setinfo) — Sets the data associated with the current iterator entry * [SplObjectStorage::unserialize](splobjectstorage.unserialize) — Unserializes a storage from its string representation * [SplObjectStorage::valid](splobjectstorage.valid) — Returns if the current iterator entry is valid php IntlCalendar::getErrorMessage IntlCalendar::getErrorMessage ============================= intlcal\_get\_error\_message ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getErrorMessage -- intlcal\_get\_error\_message — Get last error message on the object ### Description Object-oriented style (method): ``` public IntlCalendar::getErrorMessage(): string|false ``` Procedural style: ``` intlcal_get_error_message(IntlCalendar $calendar): string|false ``` Returns the error message (if any) associated with the error reported by [IntlCalendar::getErrorCode()](intlcalendar.geterrorcode) or [intlcal\_get\_error\_code()](intlcalendar.geterrorcode). If there is no associated error message, only the string representation of the name of the error constant will be returned. Otherwise, the message also includes a message set on the side of the PHP binding. ### Parameters `calendar` The calendar object, on the procedural style interface. ### Return Values The error message associated with last error that occurred in a function call on this object, or a string indicating the non-existence of an error. Returns **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getErrorMessage()**** ``` <?php $cal = IntlCalendar::createInstance('UTC', 'en_US'); var_dump($cal->getErrorMessage()); $cal->getWeekendTransition(IntlCalendar::DOW_WEDNESDAY); var_dump($cal->getErrorMessage()); ``` The above example will output: ``` string(12) "U_ZERO_ERROR" string(82) "intlcal_get_weekend_transition: Error calling ICU method: U_ILLEGAL_ARGUMENT_ERROR" ``` php IntlChar::totitle IntlChar::totitle ================= (PHP 7, PHP 8) IntlChar::totitle — Make Unicode character titlecase ### Description ``` public static IntlChar::totitle(int|string $codepoint): int|string|null ``` The given character is mapped to its titlecase equivalent. If the character has no titlecase equivalent, the original character itself is returned. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns the Simple\_Titlecase\_Mapping of the code point, if any; otherwise the code point itself. Returns **`null`** on failure. The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::totitle("A")); var_dump(IntlChar::totitle("a")); var_dump(IntlChar::totitle("Φ")); var_dump(IntlChar::totitle("φ")); var_dump(IntlChar::totitle("1")); var_dump(IntlChar::totitle(ord("A"))); var_dump(IntlChar::totitle(ord("a"))); ?> ``` The above example will output: ``` string(1) "A" string(1) "A" string(2) "Φ" string(2) "Φ" string(1) "1" int(65) int(65) ``` ### See Also * [IntlChar::tolower()](intlchar.tolower) - Make Unicode character lowercase * [IntlChar::toupper()](intlchar.toupper) - Make Unicode character uppercase * [mb\_convert\_case()](function.mb-convert-case) - Perform case folding on a string php The DOMCdataSection class The DOMCdataSection class ========================= Introduction ------------ (PHP 5, PHP 7, PHP 8) The **DOMCdataSection** inherits from [DOMText](class.domtext) for textural representation of CData constructs. Class synopsis -------------- class **DOMCdataSection** extends [DOMText](class.domtext) { /\* Inherited properties \*/ public readonly string [$wholeText](class.domtext#domtext.props.wholetext); public string [$data](class.domcharacterdata#domcharacterdata.props.data); public readonly int [$length](class.domcharacterdata#domcharacterdata.props.length); public readonly ?[DOMElement](class.domelement) [$previousElementSibling](class.domcharacterdata#domcharacterdata.props.previouselementsibling); public readonly ?[DOMElement](class.domelement) [$nextElementSibling](class.domcharacterdata#domcharacterdata.props.nextelementsibling); public readonly string [$nodeName](class.domnode#domnode.props.nodename); public ?string [$nodeValue](class.domnode#domnode.props.nodevalue); public readonly int [$nodeType](class.domnode#domnode.props.nodetype); public readonly ?[DOMNode](class.domnode) [$parentNode](class.domnode#domnode.props.parentnode); public readonly [DOMNodeList](class.domnodelist) [$childNodes](class.domnode#domnode.props.childnodes); public readonly ?[DOMNode](class.domnode) [$firstChild](class.domnode#domnode.props.firstchild); public readonly ?[DOMNode](class.domnode) [$lastChild](class.domnode#domnode.props.lastchild); public readonly ?[DOMNode](class.domnode) [$previousSibling](class.domnode#domnode.props.previoussibling); public readonly ?[DOMNode](class.domnode) [$nextSibling](class.domnode#domnode.props.nextsibling); public readonly ?[DOMNamedNodeMap](class.domnamednodemap) [$attributes](class.domnode#domnode.props.attributes); public readonly ?[DOMDocument](class.domdocument) [$ownerDocument](class.domnode#domnode.props.ownerdocument); public readonly ?string [$namespaceURI](class.domnode#domnode.props.namespaceuri); public string [$prefix](class.domnode#domnode.props.prefix); public readonly ?string [$localName](class.domnode#domnode.props.localname); public readonly ?string [$baseURI](class.domnode#domnode.props.baseuri); public string [$textContent](class.domnode#domnode.props.textcontent); /\* Methods \*/ public [\_\_construct](domcdatasection.construct)(string `$data`) /\* Inherited methods \*/ ``` public DOMText::isElementContentWhitespace(): bool ``` ``` public DOMText::isWhitespaceInElementContent(): bool ``` ``` public DOMText::splitText(int $offset): DOMText|false ``` ``` public DOMCharacterData::appendData(string $data): bool ``` ``` public DOMCharacterData::deleteData(int $offset, int $count): bool ``` ``` public DOMCharacterData::insertData(int $offset, string $data): bool ``` ``` public DOMCharacterData::replaceData(int $offset, int $count, string $data): bool ``` ``` public DOMCharacterData::substringData(int $offset, int $count): string|false ``` ``` public DOMNode::appendChild(DOMNode $node): DOMNode|false ``` ``` public DOMNode::C14N( bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): string|false ``` ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` ``` public DOMNode::cloneNode(bool $deep = false): DOMNode|false ``` ``` public DOMNode::getLineNo(): int ``` ``` public DOMNode::getNodePath(): ?string ``` ``` public DOMNode::hasAttributes(): bool ``` ``` public DOMNode::hasChildNodes(): bool ``` ``` public DOMNode::insertBefore(DOMNode $node, ?DOMNode $child = null): DOMNode|false ``` ``` public DOMNode::isDefaultNamespace(string $namespace): bool ``` ``` public DOMNode::isSameNode(DOMNode $otherNode): bool ``` ``` public DOMNode::isSupported(string $feature, string $version): bool ``` ``` public DOMNode::lookupNamespaceUri(string $prefix): string ``` ``` public DOMNode::lookupPrefix(string $namespace): ?string ``` ``` public DOMNode::normalize(): void ``` ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` ``` public DOMNode::replaceChild(DOMNode $node, DOMNode $child): DOMNode|false ``` } Table of Contents ----------------- * [DOMCdataSection::\_\_construct](domcdatasection.construct) — Constructs a new DOMCdataSection object
programming_docs
php interface_exists interface\_exists ================= (PHP 5 >= 5.0.2, PHP 7, PHP 8) interface\_exists — Checks if the interface has been defined ### Description ``` interface_exists(string $interface, bool $autoload = true): bool ``` Checks if the given interface has been defined. ### Parameters `interface` The interface name `autoload` Whether to call [\_\_autoload](language.oop5.autoload) or not by default. ### Return Values Returns **`true`** if the interface given by `interface` has been defined, **`false`** otherwise. ### Examples **Example #1 **interface\_exists()** example** ``` <?php // Check the interface exists before trying to use it if (interface_exists('MyInterface')) {     class MyClass implements MyInterface     {         // Methods     } } ?> ``` ### See Also * [get\_declared\_interfaces()](function.get-declared-interfaces) - Returns an array of all declared interfaces * [class\_implements()](function.class-implements) - Return the interfaces which are implemented by the given class or interface * [class\_exists()](function.class-exists) - Checks if the class has been defined * [enum\_exists()](function.enum-exists) - Checks if the enum has been defined php Yaf_Request_Http::__construct Yaf\_Request\_Http::\_\_construct ================================= (Yaf >=1.0.0) Yaf\_Request\_Http::\_\_construct — Constructor of Yaf\_Request\_Http ### Description public **Yaf\_Request\_Http::\_\_construct**(string `$request_uri` = ?, string `$base_uri` = ?) **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php openssl_get_cert_locations openssl\_get\_cert\_locations ============================= (PHP 5 >= 5.6.0, PHP 7, PHP 8) openssl\_get\_cert\_locations — Retrieve the available certificate locations ### Description ``` openssl_get_cert_locations(): array ``` **openssl\_get\_cert\_locations()** returns an array with information about the available certificate locations that will be searched for SSL certificates. ### Parameters This function has no parameters. ### Return Values Returns an array with the available certificate locations. ### Examples **Example #1 **openssl\_get\_cert\_locations()** example** ``` <?php var_dump(openssl_get_cert_locations()); ?> ``` The above example will output: ``` array(8) { ["default_cert_file"]=> string(21) "/usr/lib/ssl/cert.pem" ["default_cert_file_env"]=> string(13) "SSL_CERT_FILE" ["default_cert_dir"]=> string(18) "/usr/lib/ssl/certs" ["default_cert_dir_env"]=> string(12) "SSL_CERT_DIR" ["default_private_dir"]=> string(20) "/usr/lib/ssl/private" ["default_default_cert_area"]=> string(12) "/usr/lib/ssl" ["ini_cafile"]=> string(0) "" ["ini_capath"]=> string(0) "" } ``` php DateTimeImmutable::sub DateTimeImmutable::sub ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) DateTimeImmutable::sub — Subtracts an amount of days, months, years, hours, minutes and seconds ### Description ``` public DateTimeImmutable::sub(DateInterval $interval): DateTimeImmutable ``` Returns a new [DateTimeImmutable](class.datetimeimmutable) object, with the specified [DateInterval](class.dateinterval) object subtracted from the specified DateTimeImmutable object. ### Parameters `interval` A [DateInterval](class.dateinterval) object ### Return Values Returns a new [DateTimeImmutable](class.datetimeimmutable) object with the modified data. ### Examples **Example #1 **DateTimeImmutable::sub()** example** Object-oriented style ``` <?php $date = new DateTimeImmutable('2000-01-20'); $newDate = $date->sub(new DateInterval('P10D')); echo $newDate->format('Y-m-d') . "\n"; ?> ``` The above examples will output: ``` 2000-01-10 ``` **Example #2 Further **DateTimeImmutable::sub()** examples** ``` <?php $date = new DateTimeImmutable('2000-01-20'); $newDate = $date->sub(new DateInterval('PT10H30S')); echo $newDate->format('Y-m-d H:i:s') . "\n"; $date = new DateTimeImmutable('2000-01-20'); $newDate = $date->sub(new DateInterval('P7Y5M4DT4H3M2S')); echo $newDate->format('Y-m-d H:i:s') . "\n"; ?> ``` The above example will output: ``` 2000-01-19 13:59:30 1992-08-15 19:56:58 ``` **Example #3 Beware when subtracting months** ``` <?php $date = new DateTimeImmutable('2001-04-30'); $interval = new DateInterval('P1M'); $newDate1 = $date->sub($interval); echo $newDate1->format('Y-m-d') . "\n"; $newDate2 = $newDate1->sub($interval); echo $newDate2->format('Y-m-d') . "\n"; ?> ``` The above example will output: ``` 2001-03-30 2001-03-02 ``` ### See Also * [DateTimeImmutable::add()](datetimeimmutable.add) - Returns a new object, with added amount of days, months, years, hours, minutes and seconds * [DateTimeImmutable::diff()](datetime.diff) - Returns the difference between two DateTime objects * [DateTimeImmutable::modify()](datetimeimmutable.modify) - Creates a new object with modified timestamp php str_repeat str\_repeat =========== (PHP 4, PHP 5, PHP 7, PHP 8) str\_repeat — Repeat a string ### Description ``` str_repeat(string $string, int $times): string ``` Returns `string` repeated `times` times. ### Parameters `string` The string to be repeated. `times` Number of time the `string` string should be repeated. `times` has to be greater than or equal to 0. If the `times` is set to 0, the function will return an empty string. ### Return Values Returns the repeated string. ### Examples **Example #1 **str\_repeat()** example** ``` <?php echo str_repeat("-=", 10); ?> ``` The above example will output: ``` -=-=-=-=-=-=-=-=-=-= ``` ### See Also * [for](control-structures.for) * [str\_pad()](function.str-pad) - Pad a string to a certain length with another string * [substr\_count()](function.substr-count) - Count the number of substring occurrences php Reflection::export Reflection::export ================== (PHP 5, PHP 7) Reflection::export — Exports **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static Reflection::export(Reflector $reflector, bool $return = false): string ``` Exports a reflection. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `reflector` The reflection to export. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values If the `return` parameter is set to **`true`**, then the export is returned as a string, otherwise **`null`** is returned. ### See Also * [Reflection::getModifierNames()](reflection.getmodifiernames) - Gets modifier names php XMLWriter::openMemory XMLWriter::openMemory ===================== xmlwriter\_open\_memory ======================= (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::openMemory -- xmlwriter\_open\_memory — Create new xmlwriter using memory for string output ### Description Object-oriented style ``` public XMLWriter::openMemory(): bool ``` Procedural style ``` xmlwriter_open_memory(): XMLWriter|false ``` Creates a new [XMLWriter](class.xmlwriter) using memory for string output. ### Parameters ### Return Values Object-oriented style: Returns **`true`** on success or **`false`** on failure. Procedural style: Returns a new [XMLWriter](class.xmlwriter) for later use with the xmlwriter functions on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | This function returns now an [XMLWriter](class.xmlwriter) instance on success. Previouly, a [resource](language.types.resource) has been returned in this case. | ### See Also * [XMLWriter::openUri()](xmlwriter.openuri) - Create new xmlwriter using source uri for output php posix_getpgrp posix\_getpgrp ============== (PHP 4, PHP 5, PHP 7, PHP 8) posix\_getpgrp — Return the current process group identifier ### Description ``` posix_getpgrp(): int ``` Return the process group identifier of the current process. ### Parameters This function has no parameters. ### Return Values Returns the identifier, as an int. ### See Also * POSIX.1 and the getpgrp(2) manual page on the POSIX system for more information on process groups. php header_register_callback header\_register\_callback ========================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) header\_register\_callback — Call a header function ### Description ``` header_register_callback(callable $callback): bool ``` Registers a function that will be called when PHP starts sending output. The `callback` is executed just after PHP prepares all headers to be sent, and before any other output is sent, creating a window to manipulate the outgoing headers before being sent. ### Parameters `callback` Function called just before the headers are sent. It gets no parameters and the return value is ignored. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **header\_register\_callback()** example** ``` <?php header('Content-Type: text/plain'); header('X-Test: foo'); function foo() {  foreach (headers_list() as $header) {    if (strpos($header, 'X-Powered-By:') !== false) {      header_remove('X-Powered-By');    }    header_remove('X-Test');  } } $result = header_register_callback('foo'); echo "a"; ?> ``` The above example will output something similar to: ``` Content-Type: text/plain a ``` ### Notes **header\_register\_callback()** is executed just as the headers are about to be sent out, so any output from this function can break output. > > **Note**: > > > Headers will only be accessible and output when a SAPI that supports them is in use. > > ### See Also * [headers\_list()](function.headers-list) - Returns a list of response headers sent (or ready to send) * [header\_remove()](function.header-remove) - Remove previously set headers * [header()](function.header) - Send a raw HTTP header php ReflectionProperty::__clone ReflectionProperty::\_\_clone ============================= (PHP 5, PHP 7, PHP 8) ReflectionProperty::\_\_clone — Clone ### Description ``` private ReflectionProperty::__clone(): void ``` Clones. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This method is no longer final. | ### See Also * [ReflectionProperty::export()](reflectionproperty.export) - Export * [Object cloning](language.oop5.cloning) php GmagickDraw::setstrokeopacity GmagickDraw::setstrokeopacity ============================= (PECL gmagick >= Unknown) GmagickDraw::setstrokeopacity — Specifies the opacity of stroked object outlines ### Description ``` public GmagickDraw::setstrokeopacity(float $stroke_opacity): GmagickDraw ``` Specifies the opacity of stroked object outlines. ### Parameters `stroke_opacity` Stroke opacity. The value 1.0 is opaque. ### Return Values The [GmagickDraw](class.gmagickdraw) object. php Yaf_Application::setAppDirectory Yaf\_Application::setAppDirectory ================================= (Yaf >=2.1.4) Yaf\_Application::setAppDirectory — Change the application directory ### Description ``` public Yaf_Application::setAppDirectory(string $directory): Yaf_Application ``` ### Parameters `directory` ### Return Values php mb_language mb\_language ============ (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_language — Set/Get current language ### Description ``` mb_language(?string $language = null): string|bool ``` Set/Get the current language. ### Parameters `language` Used for encoding e-mail messages. The valid languages are listed in the following table. [mb\_send\_mail()](function.mb-send-mail) uses this setting to encode e-mail. | Language | Charset | Encoding | Alias | | --- | --- | --- | --- | | German/de | ISO-8859-15 | Quoted-Printable | Deutsch | | English/en | ISO-8859-1 | Quoted-Printable | | | Armenian/hy | ArmSCII-8 | Quoted-Printable | | | Japanese/ja | ISO-2022-JP | BASE64 | | | Korean/ko | ISO-2022-KR | BASE64 | | | neutral | UTF-8 | BASE64 | | | Russian/ru | KOI8-R | Quoted-Printable | | | Turkish/tr | ISO-8859-9 | Quoted-Printable | | | Ukrainian/ua | KOI8-U | Quoted-Printable | | | uni | UTF-8 | BASE64 | universal | | Simplified Chinese/zh-cn | HZ | BASE64 | | | Traditional Chinese/zh-tw | BIG-5 | BASE64 | | ### Return Values If `language` is set and `language` is valid, it returns **`true`**. Otherwise, it returns **`false`**. When `language` is omitted or **`null`**, it returns the language name as a string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `language` is nullable now. | ### See Also * [mb\_send\_mail()](function.mb-send-mail) - Send encoded mail php Collectable::isGarbage Collectable::isGarbage ====================== (PECL pthreads >= 2.0.8) Collectable::isGarbage — Determine whether an object has been marked as garbage ### Description ``` public Collectable::isGarbage(): bool ``` Can be called in [Pool::collect()](pool.collect) to determine if this object is garbage. ### Parameters This function has no parameters. ### Return Values Always returns **`true`**. ### See Also * [Pool::collect()](pool.collect) - Collect references to completed tasks php sqlsrv_close sqlsrv\_close ============= (No version information available, might only be in Git) sqlsrv\_close — Closes an open connection and releases resourses associated with the connection ### Description ``` sqlsrv_close(resource $conn): bool ``` Closes an open connection and releases resourses associated with the connection. ### Parameters `conn` The connection to be closed. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **sqlsrv\_close()** example** ``` <?php $serverName = "serverName\sqlexpres"; $connOptions = array("UID"=>"username", "PWD"=>"password", "Database"=>"dbname"); $conn = sqlsrv_connect( $serverName, $connOptions ); if( $conn === false ) {      die( print_r( sqlsrv_errors(), true)); } //------------------------------------- // Perform database operations here. //------------------------------------- // Close the connection. sqlsrv_close( $conn ); ?> ``` ### See Also * [sqlsrv\_connect()](function.sqlsrv-connect) - Opens a connection to a Microsoft SQL Server database php gmp_scan0 gmp\_scan0 ========== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_scan0 — Scan for 0 ### Description ``` gmp_scan0(GMP|int|string $num1, int $start): int ``` Scans `num1`, starting with bit `start`, towards more significant bits, until the first clear bit is found. ### Parameters `num1` The number to scan. A [GMP](class.gmp) object, an int or a numeric string. `start` The starting bit. ### Return Values Returns the index of the found bit, as an int. The index starts from 0. ### Examples **Example #1 **gmp\_scan0()** example** ``` <?php // "0" bit is found at position 3. index starts at 0 $s1 = gmp_init("10111", 2); echo gmp_scan0($s1, 0) . "\n"; // "0" bit is found at position 7. index starts at 5 $s2 = gmp_init("101110000", 2); echo gmp_scan0($s2, 5) . "\n"; ?> ``` The above example will output: ``` 3 7 ``` php SolrQuery::setFacetDateGap SolrQuery::setFacetDateGap ========================== (PECL solr >= 0.9.2) SolrQuery::setFacetDateGap — Maps to facet.date.gap ### Description ``` public SolrQuery::setFacetDateGap(string $value, string $field_override = ?): SolrQuery ``` Maps to facet.date.gap ### Parameters `value` See facet.date.gap `field_override` The name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. php Imagick::clipImage Imagick::clipImage ================== (PECL imagick 2, PECL imagick 3) Imagick::clipImage — Clips along the first path from the 8BIM profile ### Description ``` public Imagick::clipImage(): bool ``` Clips along the first path from the 8BIM profile, if present. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php Gmagick::scaleimage Gmagick::scaleimage =================== (PECL gmagick >= Unknown) Gmagick::scaleimage — Scales the size of an image ### Description ``` public Gmagick::scaleimage(int $width, int $height, bool $fit = false): Gmagick ``` Scales the size of an image to the given dimensions. The other parameter will be calculated if 0 is passed as either param. ### Parameters `width` The number of columns in the scaled image. `height` The number of rows in the scaled image. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php FilterIterator::accept FilterIterator::accept ====================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) FilterIterator::accept — Check whether the current element of the iterator is acceptable ### Description ``` public FilterIterator::accept(): bool ``` Returns whether the current element of the iterator is acceptable through this filter. ### Parameters This function has no parameters. ### Return Values **`true`** if the current element is acceptable, otherwise **`false`**. ### Examples **Example #1 **FilterIterator::accept()** example** ``` <?php // This iterator filters all values with less than 10 characters class LengthFilterIterator extends FilterIterator {     public function accept() {         // Only accept strings with a length of 10 and greater         return strlen(parent::current()) >= 10;     } } $arrayIterator = new ArrayIterator(array('test1', 'more than 10 characters')); $lengthFilter = new LengthFilterIterator($arrayIterator); foreach ($lengthFilter as $value) {     echo $value . "\n"; } ?> ``` The above example will output: ``` more than 10 characters ``` php GearmanWorker::getErrno GearmanWorker::getErrno ======================= (PECL gearman >= 0.5.0) GearmanWorker::getErrno — Get errno ### Description ``` public GearmanWorker::getErrno(): int ``` Returns the value of errno in the case of a GEARMAN\_ERRNO return value. ### Parameters This function has no parameters. ### Return Values A valid errno. ### See Also * [GearmanWorker::error()](gearmanworker.error) - Get the last error encountered php ResourceBundle::getErrorCode ResourceBundle::getErrorCode ============================ resourcebundle\_get\_error\_code ================================ (PHP 5 >= 5.3.2, PHP 7, PHP 8, PECL intl >= 2.0.0) ResourceBundle::getErrorCode -- resourcebundle\_get\_error\_code — Get bundle's last error code ### Description Object-oriented style ``` public ResourceBundle::getErrorCode(): int ``` Procedural style ``` resourcebundle_get_error_code(ResourceBundle $bundle): int ``` Get error code from the last function performed by the bundle object. ### Parameters `bundle` [ResourceBundle](class.resourcebundle) object. ### Return Values Returns error code from last bundle object call. ### Examples **Example #1 **resourcebundle\_get\_error\_code()** example** ``` <?php $r = resourcebundle_create( 'es', "/usr/share/data/myapp"); echo $r['somestring']; if(intl_is_failure(resourcebundle_get_error_code($r))) {     report_error("Bundle error"); } ?> ``` **Example #2 OO example** ``` <?php $r = new ResourceBundle( 'es', "/usr/share/data/myapp"); echo $r['somestring']; if(intl_is_failure(ResourceBundle::getErrorCode($r))) {     report_error("Bundle error"); } ?> ``` ### See Also * [resourcebundle\_get\_error\_message()](resourcebundle.geterrormessage) - Get bundle's last error message * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure
programming_docs
php DirectoryIterator::seek DirectoryIterator::seek ======================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) DirectoryIterator::seek — Seek to a DirectoryIterator item ### Description ``` public DirectoryIterator::seek(int $offset): void ``` Seek to a given position in the [DirectoryIterator](class.directoryiterator). ### Parameters `offset` The zero-based numeric position to seek to. ### Return Values No value is returned. ### Examples **Example #1 **DirectoryIterator::seek()** example** Seek to the fourth item in the directory containing the script. The first two are usually `.` and `..` ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); $iterator->seek(3); if ($iterator->valid()) {     echo $iterator->getFilename(); } else {     echo 'No file at position 3'; } ?> ``` ### See Also * [DirectoryIterator::rewind()](directoryiterator.rewind) - Rewind the DirectoryIterator back to the start * [DirectoryIterator::next()](directoryiterator.next) - Move forward to next DirectoryIterator item * [SeekableIterator::seek()](seekableiterator.seek) - Seeks to a position php openssl_pkcs7_read openssl\_pkcs7\_read ==================== (PHP 7 >= 7.2.0, PHP 8) openssl\_pkcs7\_read — Export the PKCS7 file to an array of PEM certificates ### Description ``` openssl_pkcs7_read(string $data, array &$certificates): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `data` The string of data you wish to parse (p7b format). `certificates` The array of PEM certificates from the p7b input data. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Get a PEM array from a P7B file** ``` <?php $file = 'certs.p7b'; $f = file_get_contents($file); $p7 = array(); $r = openssl_pkcs7_read($f, $p7); if ($r === false) {     printf("ERROR: %s is not a proper p7b file".PHP_EOL, $file);         for($e = openssl_error_string(), $i = 0; $e; $e = openssl_error_string(), $i++)             printf("SSL l%d: %s".PHP_EOL, $i, $e);     exit(1); } print_r($p7); ?> ``` ### See Also * [openssl\_csr\_sign()](function.openssl-csr-sign) - Sign a CSR with another certificate (or itself) and generate a certificate php SplObjectStorage::rewind SplObjectStorage::rewind ======================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplObjectStorage::rewind — Rewind the iterator to the first storage element ### Description ``` public SplObjectStorage::rewind(): void ``` Rewind the iterator to the first storage element. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **SplObjectStorage::rewind()** example** ``` <?php $s = new SplObjectStorage(); $o1 = new StdClass; $o2 = new StdClass; $s->attach($o1, "d1"); $s->attach($o2, "d2"); $s->rewind(); while($s->valid()) {     $index  = $s->key();     $object = $s->current(); // similar to current($s)     $data   = $s->getInfo();     var_dump($object);     var_dump($data);     $s->next(); } ?> ``` The above example will output something similar to: ``` int(1) int(0) ``` ### See Also * [SplObjectStorage::next()](splobjectstorage.next) - Move to the next entry php DOMDocument::createElement DOMDocument::createElement ========================== (PHP 5, PHP 7, PHP 8) DOMDocument::createElement — Create new element node ### Description ``` public DOMDocument::createElement(string $localName, string $value = ""): DOMElement|false ``` This function creates a new instance of class [DOMElement](class.domelement). This node will not show up in the document unless it is inserted with (e.g.) [DOMNode::appendChild()](domnode.appendchild). ### Parameters `localName` The tag name of the element. `value` The value of the element. By default, an empty element will be created. The value can also be set later with [DOMElement::$nodeValue](class.domnode#domnode.props.nodevalue). The value is used verbatim except that the < and > entity references will escaped. Note that & has to be manually escaped; otherwise it is regarded as starting an entity reference. Also " won't be escaped. ### Return Values Returns a new instance of class [DOMElement](class.domelement) or **`false`** if an error occurred. ### Errors/Exceptions **`DOM_INVALID_CHARACTER_ERR`** Raised if `localName` contains an invalid character. ### Examples **Example #1 Creating a new element and inserting it as root** ``` <?php $dom = new DOMDocument('1.0', 'utf-8'); $element = $dom->createElement('test', 'This is the root element!'); // We insert the new element as root (child of the document) $dom->appendChild($element); echo $dom->saveXML(); ?> ``` The above example will output: ``` <?xml version="1.0" encoding="utf-8"?> <test>This is the root element!</test> ``` **Example #2 Passing text containing an unescaped & as `value`** ``` <?php $dom = new DOMDocument('1.0', 'utf-8'); $element = $dom->createElement('foo', 'me & you'); $dom->appendChild($element); echo $dom->saveXML(); ?> ``` The above example will output something similar to: ``` Warning: DOMDocument::createElement(): unterminated entity reference you in /in/BjTCg on line 4 <?xml version="1.0" encoding="utf-8"?> <foo/> ``` ### Notes > > **Note**: > > > The `value` will *not* be escaped. Use [DOMDocument::createTextNode()](domdocument.createtextnode) to create a text node with *escaping support*. > > ### See Also * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children * [DOMDocument::createAttribute()](domdocument.createattribute) - Create new attribute * [DOMDocument::createAttributeNS()](domdocument.createattributens) - Create new attribute node with an associated namespace * [DOMDocument::createCDATASection()](domdocument.createcdatasection) - Create new cdata node * [DOMDocument::createComment()](domdocument.createcomment) - Create new comment node * [DOMDocument::createDocumentFragment()](domdocument.createdocumentfragment) - Create new document fragment * [DOMDocument::createElementNS()](domdocument.createelementns) - Create new element node with an associated namespace * [DOMDocument::createEntityReference()](domdocument.createentityreference) - Create new entity reference node * [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node * [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node php class_alias class\_alias ============ (PHP 5 >= 5.3.0, PHP 7, PHP 8) class\_alias — Creates an alias for a class ### Description ``` class_alias(string $class, string $alias, bool $autoload = true): bool ``` Creates an alias named `alias` based on the user defined class `class`. The aliased class is exactly the same as the original class. ### Parameters `class` The original class. `alias` The alias name for the class. `autoload` Whether to autoload if the original class is not found. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **class\_alias()** example** ``` <?php class foo { } class_alias('foo', 'bar'); $a = new foo; $b = new bar; // the objects are the same var_dump($a == $b, $a === $b); var_dump($a instanceof $b); // the classes are the same var_dump($a instanceof foo); var_dump($a instanceof bar); var_dump($b instanceof foo); var_dump($b instanceof bar); ?> ``` The above example will output: ``` bool(true) bool(false) bool(true) bool(true) bool(true) bool(true) bool(true) ``` ### See Also * [get\_parent\_class()](function.get-parent-class) - Retrieves the parent class name for object or class * [is\_subclass\_of()](function.is-subclass-of) - Checks if the object has this class as one of its parents or implements it php wincache_fcache_fileinfo wincache\_fcache\_fileinfo ========================== (PECL wincache >= 1.0.0) wincache\_fcache\_fileinfo — Retrieves information about files cached in the file cache ### Description ``` wincache_fcache_fileinfo(bool $summaryonly = false): array|false ``` Retrieves information about file cache content and its usage. ### Parameters `summaryonly` Controls whether the returned array will contain information about individual cache entries along with the file cache summary. ### Return Values Array of meta data about file cache or **`false`** on failure The array returned by this function contains the following elements: * `total_cache_uptime` - total time in seconds that the file cache has been active * `total_file_count` - total number of files that are currently in the file cache * `total_hit_count` - number of times the files have been served from the file cache * `total_miss_count` - number of times the files have not been found in the file cache * `file_entries` - an array that contains the information about all the cached files: + `file_name` - absolute file name of the cached file + `add_time` - time in seconds since the file has been added to the file cache + `use_time` - time in seconds since the file has been accessed in the file cache + `last_check` - time in seconds since the file has been checked for modifications + `hit_count` - number of times the file has been served from the cache + `file_size` - size of the cached file in bytes ### Examples **Example #1 A **wincache\_fcache\_fileinfo()** example** ``` <pre> <?php print_r(wincache_fcache_fileinfo()); ?> </pre> ``` The above example will output: ``` Array ( [total_cache_uptime] => 3234 [total_file_count] => 5 [total_hit_count] => 0 [total_miss_count] => 1 [file_entries] => Array ( [1] => Array ( [file_name] => c:\inetpub\wwwroot\checkcache.php [add_time] => 1 [use_time] => 0 [last_check] => 1 [hit_count] => 1 [file_size] => 2435 ) [2] => Array (...iterates for each cached file) ) ) ``` ### See Also * [wincache\_fcache\_meminfo()](function.wincache-fcache-meminfo) - Retrieves information about file cache memory usage * [wincache\_ocache\_fileinfo()](function.wincache-ocache-fileinfo) - Retrieves information about files cached in the opcode cache * [wincache\_ocache\_meminfo()](function.wincache-ocache-meminfo) - Retrieves information about opcode cache memory usage * [wincache\_rplist\_fileinfo()](function.wincache-rplist-fileinfo) - Retrieves information about resolve file path cache * [wincache\_rplist\_meminfo()](function.wincache-rplist-meminfo) - Retrieves information about memory usage by the resolve file path cache * [wincache\_refresh\_if\_changed()](function.wincache-refresh-if-changed) - Refreshes the cache entries for the cached files * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [wincache\_scache\_info()](function.wincache-scache-info) - Retrieves information about files cached in the session cache * [wincache\_scache\_meminfo()](function.wincache-scache-meminfo) - Retrieves information about session cache memory usage php Imagick::getPage Imagick::getPage ================ (PECL imagick 2, PECL imagick 3) Imagick::getPage — Returns the page geometry ### Description ``` public Imagick::getPage(): array ``` Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y". ### Parameters This function has no parameters. ### Return Values Returns the page geometry associated with the Imagick object in an associative array with the keys "width", "height", "x", and "y", throwing ImagickException on error. php Yaf_View_Simple::assignRef Yaf\_View\_Simple::assignRef ============================ (Yaf >=1.0.0) Yaf\_View\_Simple::assignRef — The assignRef purpose ### Description ``` public Yaf_View_Simple::assignRef(string $name, mixed &$value): bool ``` unlike [Yaf\_View\_Simple::assign()](yaf-view-simple.assign), this method assign a ref value to engine. ### Parameters `name` A string name which will be used to access the value in the tempalte. `value` mixed value ### Return Values ### Examples **Example #1 **Yaf\_View\_Simple::assignRef()**example** ``` <?php class IndexController extends Yaf_Controller_Abstract {     public function indexAction() {         $value = "bar";         $this->getView()->assign("foo", $value);         /* plz note that there was a bug before Yaf 2.1.4,           * which make following output "bar";          */         $dummy = $this->getView()->render("index/index.phtml");         echo $value;         //prevent the auto-render         Yaf_Dispatcher::getInstance()->autoRender(FALSE);     } } ?> ``` **Example #2 **template()**example** ``` <html>  <head>   <title><?php echo $foo;  $foo = "changed"; ?></title>  </head>   <body> </body> </html> ``` The above example will output something similar to: ``` /* access the index controller will result: */ changed ``` ### See Also * [Yaf\_View\_Simple::assign()](yaf-view-simple.assign) - Assign values * [Yaf\_View\_Simple::\_\_set()](yaf-view-simple.set) - Set value to engine php pcntl_exec pcntl\_exec =========== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pcntl\_exec — Executes specified program in current process space ### Description ``` pcntl_exec(string $path, array $args = [], array $env_vars = []): bool ``` Executes the program with the given arguments. ### Parameters `path` `path` must be the path to a binary executable or a script with a valid path pointing to an executable in the shebang ( #!/usr/local/bin/perl for example) as the first line. See your system's man execve(2) page for additional information. `args` `args` is an array of argument strings passed to the program. `env_vars` `env_vars` is an array of strings which are passed as environment to the program. The array is in the format of name => value, the key being the name of the environmental variable and the value being the value of that variable. ### Return Values Returns **`false`**. php EventSslContext::__construct EventSslContext::\_\_construct ============================== (PECL event >= 1.2.6-beta) EventSslContext::\_\_construct — Constructs an OpenSSL context for use with Event classes ### Description ``` public EventSslContext::__construct( string $method , string $options ) ``` Creates SSL context holding pointer to `SSL_CTX` (see the system manual). ### Parameters `method` One of [`EventSslContext::*_METHOD` constants](class.eventsslcontext#eventsslcontext.constants) . `options` Associative array of SSL context options One of [`EventSslContext::OPT_*` constants](class.eventsslcontext#eventsslcontext.constants) . ### Return Values Returns [EventSslContext](class.eventsslcontext) object. ### Examples **Example #1 **EventSslContext::\_\_construct()** example** ``` <?php $ctx = new EventSslContext(EventSslContext::SSLv3_SERVER_METHOD, array(      EventSslContext::OPT_LOCAL_CERT        => $local_cert,      EventSslContext::OPT_LOCAL_PK          => $local_pk,      EventSslContext::OPT_PASSPHRASE        => "echo server",      EventSslContext::OPT_VERIFY_PEER       => true,      EventSslContext::OPT_ALLOW_SELF_SIGNED => false, )); ?> ``` php Yaf_Request_Simple::__construct Yaf\_Request\_Simple::\_\_construct =================================== (Yaf >=1.0.0) Yaf\_Request\_Simple::\_\_construct — Constructor of Yaf\_Request\_Simple ### Description public **Yaf\_Request\_Simple::\_\_construct**( string `$method` = ?, string `$module` = ?, string `$controller` = ?, string `$action` = ?, array `$params` = ? ) **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Zookeeper::getAcl Zookeeper::getAcl ================= (PECL zookeeper >= 0.1.0) Zookeeper::getAcl — Gets the acl associated with a node synchronously ### Description ``` public Zookeeper::getAcl(string $path): array ``` ### Parameters `path` The name of the node. Expressed as a file name with slashes separating ancestors of the node. ### Return Values Return acl array on success and false on failure. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or fail to get ACL of a node. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### Examples **Example #1 **Zookeeper::getAcl()** example** Get ACL of a node. ``` <?php $zookeeper = new Zookeeper('locahost:2181'); $aclArray = array(   array(     'perms'  => Zookeeper::PERM_ALL,     'scheme' => 'world',     'id'     => 'anyone',   ) ); $path = '/path/to/newnode'; $zookeeper->setAcl($path, $aclArray); $r = $zookeeper->getAcl($path); if ($r)   var_dump($r); else   echo 'ERR'; ?> ``` The above example will output: ``` array(1) { [0]=> array(3) { ["perms"]=> int(31) ["scheme"]=> string(5) "world" ["id"]=> string(6) "anyone" } } ``` ### See Also * [Zookeeper::create()](zookeeper.create) - Create a node synchronously * [Zookeeper::setAcl()](zookeeper.setacl) - Sets the acl associated with a node synchronously * [ZooKeeper Permissions](class.zookeeper#zookeeper.class.constants.perms) * [ZookeeperException](class.zookeeperexception) php getallheaders getallheaders ============= (PHP 4, PHP 5, PHP 7, PHP 8) getallheaders — Fetch all HTTP request headers ### Description ``` getallheaders(): array ``` Fetches all HTTP headers from the current request. This function is an alias for [apache\_request\_headers()](function.apache-request-headers). Please read the [apache\_request\_headers()](function.apache-request-headers) documentation for more information on how this function works. ### Parameters This function has no parameters. ### Return Values An associative array of all the HTTP headers in the current request, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | This function became available in the FPM SAPI. | ### Examples **Example #1 **getallheaders()** example** ``` <?php foreach (getallheaders() as $name => $value) {     echo "$name: $value\n"; } ?> ``` ### See Also * [apache\_response\_headers()](function.apache-response-headers) - Fetch all HTTP response headers php Ds\Map::allocate Ds\Map::allocate ================ (PECL ds >= 1.0.0) Ds\Map::allocate — Allocates enough memory for a required capacity ### Description ``` public Ds\Map::allocate(int $capacity): void ``` Allocates enough memory for a required capacity. ### Parameters `capacity` The number of values for which capacity should be allocated. > > **Note**: > > > Capacity will stay the same if this value is less than or equal to the current capacity. > > > > **Note**: > > > Capacity will always be rounded up to the nearest power of 2. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\Map::allocate()** example** ``` <?php $map = new \Ds\Map(); var_dump($map->capacity()); $map->allocate(100); var_dump($map->capacity()); ?> ``` The above example will output something similar to: ``` int(16) int(128) ```
programming_docs
php ImagickKernel::addUnityKernel ImagickKernel::addUnityKernel ============================= (PECL imagick >= 3.3.0) ImagickKernel::addUnityKernel — Description ### Description ``` public ImagickKernel::addUnityKernel(float $scale): void ``` Adds a given amount of the 'Unity' Convolution Kernel to the given pre-scaled and normalized Kernel. This in effect adds that amount of the original image into the resulting convolution kernel. The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp kernels or into sharpening kernels. ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 **ImagickKernel::addUnityKernel()**** ``` <?php     function renderKernelTable($matrix) {         $output = "<table class='infoTable'>";              foreach ($matrix as $row) {             $output .= "<tr>";             foreach ($row as $cell) {                 $output .= "<td style='text-align:left'>";                 if ($cell === false) {                     $output .= "false";                 }                 else {                     $output .= round($cell, 3);                 }                 $output .= "</td>";             }             $output .= "</tr>";         }              $output .= "</table>";              return $output;     }     $matrix = [         [-1, 0, -1],         [ 0, 4,  0],         [-1, 0, -1],     ];     $kernel = \ImagickKernel::fromMatrix($matrix);     $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);     $output = "Before adding unity kernel: <br/>";     $output .= renderKernelTable($kernel->getMatrix());     $kernel->addUnityKernel(0.5);     $output .= "After adding unity kernel: <br/>";     $output .= renderKernelTable($kernel->getMatrix());               $kernel->scale(1, \Imagick::NORMALIZE_KERNEL_VALUE);     $output .= "After renormalizing kernel: <br/>";     $output .= renderKernelTable($kernel->getMatrix());     echo $output; ?> ``` **Example #2 **ImagickKernel::addUnityKernel()**** ``` <?php function addUnityKernel($imagePath) {     $matrix = [         [-1, 0, -1],         [ 0, 4,  0],         [-1, 0, -1],     ];     $kernel = ImagickKernel::fromMatrix($matrix);     $kernel->scale(4, \Imagick::NORMALIZE_KERNEL_VALUE);     $kernel->addUnityKernel(0.5);     $imagick = new \Imagick(realpath($imagePath));     $imagick->filter($kernel);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php SplFileInfo::isFile SplFileInfo::isFile =================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::isFile — Tells if the object references a regular file ### Description ``` public SplFileInfo::isFile(): bool ``` Checks if the file referenced by this SplFileInfo object exists and is a regular file. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the file exists and is a regular file (not a link), **`false`** otherwise. ### Examples **Example #1 **SplFileInfo::isFile()** example** ``` <?php $info = new SplFileInfo(__FILE__); var_dump($info->isFile()); $info = new SplFileInfo(dirname(__FILE__)); var_dump($info->isFile()); ?> ``` The above example will output something similar to: ``` bool(true) bool(false) ``` php openssl_csr_new openssl\_csr\_new ================= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) openssl\_csr\_new — Generates a CSR ### Description ``` openssl_csr_new( array $distinguished_names, OpenSSLAsymmetricKey &$private_key, ?array $options = null, ?array $extra_attributes = null ): OpenSSLCertificateSigningRequest|false ``` **openssl\_csr\_new()** generates a new CSR (Certificate Signing Request) based on the information provided by `distinguished_names`. > **Note**: You need to have a valid openssl.cnf installed for this function to operate correctly. See the notes under [the installation section](https://www.php.net/manual/en/openssl.installation.php) for more information. > > ### Parameters `distinguished_names` The Distinguished Name or subject fields to be used in the certificate. `private_key` `private_key` should be set to a private key that was previously generated by [openssl\_pkey\_new()](function.openssl-pkey-new) (or otherwise obtained from the other openssl\_pkey family of functions). The corresponding public portion of the key will be used to sign the CSR. `options` By default, the information in your system `openssl.conf` is used to initialize the request; you can specify a configuration file section by setting the `config_section_section` key of `options`. You can also specify an alternative openssl configuration file by setting the value of the `config` key to the path of the file you want to use. The following keys, if present in `options` behave as their equivalents in the `openssl.conf`, as listed in the table below. **Configuration overrides**| `options` key | type | `openssl.conf` equivalent | description | | --- | --- | --- | --- | | digest\_alg | string | default\_md | Digest method or signature hash, usually one of [openssl\_get\_md\_methods()](function.openssl-get-md-methods) | | x509\_extensions | string | x509\_extensions | Selects which extensions should be used when creating an x509 certificate | | req\_extensions | string | req\_extensions | Selects which extensions should be used when creating a CSR | | private\_key\_bits | int | default\_bits | Specifies how many bits should be used to generate a private key | | private\_key\_type | int | none | Specifies the type of private key to create. This can be one of **`OPENSSL_KEYTYPE_DSA`**, **`OPENSSL_KEYTYPE_DH`**, **`OPENSSL_KEYTYPE_RSA`** or **`OPENSSL_KEYTYPE_EC`**. The default value is **`OPENSSL_KEYTYPE_RSA`**. | | encrypt\_key | bool | encrypt\_key | Should an exported key (with passphrase) be encrypted? | | encrypt\_key\_cipher | int | none | One of [cipher constants](https://www.php.net/manual/en/openssl.ciphers.php). | | curve\_name | string | none | One of [openssl\_get\_curve\_names()](function.openssl-get-curve-names). | | config | string | N/A | Path to your own alternative openssl.conf file. | `extra_attributes` `extra_attributes` is used to specify additional configuration options for the CSR. Both `distinguished_names` and `extra_attributes` are associative arrays whose keys are converted to OIDs and applied to the relevant part of the request. ### Return Values Returns the CSR or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [OpenSSLCertificateSigningRequest](class.opensslcertificatesigningrequest) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509 CSR` was returned. | | 8.0.0 | `private_key` accepts an [OpenSSLAsymmetricKey](class.opensslasymmetrickey) instance now; previously, a [resource](language.types.resource) of type `OpenSSL key` was accepted. | | 7.1.0 | `options` now also supports `curve_name`. | ### Examples **Example #1 Creating a self-signed certificate** ``` <?php // for SSL server certificates the commonName is the domain name to be secured // for S/MIME email certificates the commonName is the owner of the email address // location and identification fields refer to the owner of domain or email subject to be secured $dn = array(     "countryName" => "GB",     "stateOrProvinceName" => "Somerset",     "localityName" => "Glastonbury",     "organizationName" => "The Brain Room Limited",     "organizationalUnitName" => "PHP Documentation Team",     "commonName" => "Wez Furlong",     "emailAddress" => "[email protected]" ); // Generate a new private (and public) key pair $privkey = openssl_pkey_new(array(     "private_key_bits" => 2048,     "private_key_type" => OPENSSL_KEYTYPE_RSA, )); // Generate a certificate signing request $csr = openssl_csr_new($dn, $privkey, array('digest_alg' => 'sha256')); // Generate a self-signed cert, valid for 365 days $x509 = openssl_csr_sign($csr, null, $privkey, $days=365, array('digest_alg' => 'sha256')); // Save your private key, CSR and self-signed cert for later use openssl_csr_export($csr, $csrout) and var_dump($csrout); openssl_x509_export($x509, $certout) and var_dump($certout); openssl_pkey_export($privkey, $pkeyout, "mypassword") and var_dump($pkeyout); // Show any errors that occurred here while (($e = openssl_error_string()) !== false) {     echo $e . "\n"; } ?> ``` **Example #2 Creating a self-signed ECC certificate (as of PHP 7.1.0)** ``` <?php $subject = array(     "commonName" => "docs.php.net", ); // Generate a new private (and public) key pair $private_key = openssl_pkey_new(array(     "private_key_type" => OPENSSL_KEYTYPE_EC,     "curve_name" => 'prime256v1', )); // Generate a certificate signing request $csr = openssl_csr_new($subject, $private_key, array('digest_alg' => 'sha384')); // Generate self-signed EC cert $x509 = openssl_csr_sign($csr, null, $private_key, $days=365, array('digest_alg' => 'sha384')); openssl_x509_export_to_file($x509, 'ecc-cert.pem'); openssl_pkey_export_to_file($private_key, 'ecc-private.key'); ?> ``` ### See Also * [openssl\_csr\_sign()](function.openssl-csr-sign) - Sign a CSR with another certificate (or itself) and generate a certificate php Parle\Lexer::insertMacro Parle\Lexer::insertMacro ======================== (PECL parle >= 0.5.1) Parle\Lexer::insertMacro — Insert regex macro ### Description ``` public Parle\Lexer::insertMacro(string $name, string $regex): void ``` Insert a regex macro, that can be later used as a shortcut and included in other regular expressions. ### Parameters `name` Name of the macros. `regex` Regular expression. ### Return Values No value is returned. php The Componere\Value class The Componere\Value class ========================= Introduction ------------ (Componere 2 >= 2.1.0) A Value represents a PHP variable of all types, including undefined Class synopsis -------------- final class **Componere\Value** { /\* Constructor \*/ public [\_\_construct](componere-value.construct)( `$default` = ?) /\* Methods \*/ ``` public setPrivate(): Value ``` ``` public setProtected(): Value ``` ``` public setStatic(): Value ``` ``` public isPrivate(): bool ``` ``` public isProtected(): bool ``` ``` public isStatic(): bool ``` ``` public hasDefault(): bool ``` } Table of Contents ----------------- * [Componere\Value::\_\_construct](componere-value.construct) — Value Construction * [Componere\Value::setPrivate](componere-value.setprivate) — Accessibility Modification * [Componere\Value::setProtected](componere-value.setprotected) — Accessibility Modification * [Componere\Value::setStatic](componere-value.setstatic) — Accessibility Modification * [Componere\Value::isPrivate](componere-value.isprivate) — Accessibility Detection * [Componere\Value::isProtected](componere-value.isprotected) — Accessibility Detection * [Componere\Value::isStatic](componere-value.isstatic) — Accessibility Detection * [Componere\Value::hasDefault](componere-value.hasdefault) — Value Interaction php Memcached::add Memcached::add ============== (PECL memcached >= 0.1.0) Memcached::add — Add an item under a new key ### Description ``` public Memcached::add(string $key, mixed $value, int $expiration = ?): bool ``` **Memcached::add()** is similar to [Memcached::set()](memcached.set), but the operation fails if the `key` already exists on the server. ### Parameters `key` The key under which to store the value. `value` The value to store. `expiration` The expiration time, defaults to 0. See [Expiration Times](https://www.php.net/manual/en/memcached.expiration.php) for more info. ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key already exists. ### See Also * [Memcached::addByKey()](memcached.addbykey) - Add an item under a new key on a specific server * [Memcached::set()](memcached.set) - Store an item * [Memcached::replace()](memcached.replace) - Replace the item under an existing key php apache_request_headers apache\_request\_headers ======================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) apache\_request\_headers — Fetch all HTTP request headers ### Description ``` apache_request_headers(): array ``` Fetches all HTTP request headers from the current request. Works in the Apache, FastCGI, CLI, and FPM webservers. ### Parameters This function has no parameters. ### Return Values An associative array of all the HTTP headers in the current request, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | This function became available in the FPM SAPI. | ### Examples **Example #1 **apache\_request\_headers()** example** ``` <?php $headers = apache_request_headers(); foreach ($headers as $header => $value) {     echo "$header: $value <br />\n"; } ?> ``` The above example will output something similar to: ``` Accept: */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 Host: www.example.com Connection: Keep-Alive ``` ### Notes > > **Note**: > > > You can also get at the value of the common CGI variables by reading them from the environment, which works whether or not you are using PHP as an Apache module. Use [phpinfo()](function.phpinfo) to see a list of all of the available [environment variables](language.variables.predefined). > > ### See Also * [apache\_response\_headers()](function.apache-response-headers) - Fetch all HTTP response headers php Imagick::readImageFile Imagick::readImageFile ====================== (PECL imagick 2, PECL imagick 3) Imagick::readImageFile — Reads image from open filehandle ### Description ``` public Imagick::readImageFile(resource $filehandle, string $fileName = null): bool ``` Reads image from open filehandle ### Parameters `filehandle` `fileName` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php Yaf_Registry::get Yaf\_Registry::get ================== (Yaf >=1.0.0) Yaf\_Registry::get — Retrieve an item from registry ### Description ``` public static Yaf_Registry::get(string $name): mixed ``` Retrieve an item from registry ### Parameters `name` ### Return Values php SQLite3Stmt::getSQL SQLite3Stmt::getSQL =================== (PHP 7 >= 7.4.0, PHP 8) SQLite3Stmt::getSQL — Get the SQL of the statement ### Description ``` public SQLite3Stmt::getSQL(bool $expand = false): string|false ``` Retrieves the SQL of the prepared statement. If `expand` is **`false`**, the unmodified SQL is retrieved. If `expand` is **`true`**, all query parameters are replaced with their bound values, or with an SQL `NULL`, if not already bound. ### Parameters `expand` Whether to retrieve the expanded SQL. Passing **`true`** is only supported as of libsqlite 3.14. ### Return Values Returns the SQL of the prepared statement, or **`false`** on failure. ### Errors/Exceptions If `expand` is **`true`**, but the libsqlite version is less than 3.14, an error of level **`E_WARNING`** or an [Exception](class.exception) is issued, according to [SQLite3::enableExceptions()](sqlite3.enableexceptions). ### Examples **Example #1 Inspecting the expanded SQL** ``` <?php $db = new SQLite3(':memory:'); $stmt = $db->prepare("SELECT :a, ?, :c"); $stmt->bindValue(':a', 'foo'); $answer = 42; $stmt->bindParam(2, $answer); var_dump($stmt->getSQL(true)); ?> ``` The above example will output something similar to: ``` string(24) "SELECT 'foo', '42', NULL" ``` php mb_stristr mb\_stristr =========== (PHP 5 >= 5.2.0, PHP 7, PHP 8) mb\_stristr — Finds first occurrence of a string within another, case insensitive ### Description ``` mb_stristr( string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null ): string|false ``` **mb\_stristr()** finds the first occurrence of `needle` in `haystack` and returns the portion of `haystack`. Unlike [mb\_strstr()](function.mb-strstr), **mb\_stristr()** is case-insensitive. If `needle` is not found, it returns **`false`**. ### Parameters `haystack` The string from which to get the first occurrence of `needle` `needle` The string to find in `haystack` `before_needle` Determines which portion of `haystack` this function returns. If set to **`true`**, it returns all of `haystack` from the beginning to the first occurrence of `needle` (excluding needle). If set to **`false`**, it returns all of `haystack` from the first occurrence of `needle` to the end (including needle). `encoding` Character encoding name to use. If it is omitted, internal character encoding is used. ### Return Values Returns the portion of `haystack`, or **`false`** if `needle` is not found. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `needle` now accepts an empty string. | | 8.0.0 | `encoding` is nullable now. | ### See Also * [stristr()](function.stristr) - Case-insensitive strstr * [strstr()](function.strstr) - Find the first occurrence of a string * [mb\_strstr()](function.mb-strstr) - Finds first occurrence of a string within another php Exception::getLine Exception::getLine ================== (PHP 5, PHP 7, PHP 8) Exception::getLine — Gets the line in which the exception was created ### Description ``` final public Exception::getLine(): int ``` Get line number where the exception was created. ### Parameters This function has no parameters. ### Return Values Returns the line number where the exception was created. ### Examples **Example #1 **Exception::getLine()** example** ``` <?php try {     throw new Exception("Some error message"); } catch(Exception $e) {     echo "The exception was created on line: " . $e->getLine(); } ?> ``` The above example will output something similar to: ``` The exception was created on line: 3 ``` ### See Also * [Throwable::getLine()](throwable.getline) - Gets the line on which the object was instantiated php SoapServer::setPersistence SoapServer::setPersistence ========================== (PHP 5, PHP 7, PHP 8) SoapServer::setPersistence — Sets SoapServer persistence mode ### Description ``` public SoapServer::setPersistence(int $mode): void ``` This function allows changing the persistence state of a SoapServer object between requests. This function allows saving data between requests utilizing PHP sessions. This method only has an affect on a SoapServer after it has exported functions utilizing [SoapServer::setClass()](soapserver.setclass). > > **Note**: > > > The persistence of **`SOAP_PERSISTENCE_SESSION`** makes only objects of the given class persistent, but not the class static data. In this case, use $this->bar instead of self::$bar. > > > > **Note**: > > > **`SOAP_PERSISTENCE_SESSION`** serializes data on the class object between requests. In order to properly utilize resources (e.g. [PDO](class.pdo)), [\_\_wakeup()](language.oop5.magic#object.wakeup) and [\_\_sleep()](language.oop5.magic#object.sleep) magic methods should be utilized. > > ### Parameters `mode` One of the `SOAP_PERSISTENCE_XXX` constants. **`SOAP_PERSISTENCE_REQUEST`** - SoapServer data does not persist between requests. This is the *default* behavior of any SoapServer object after setClass is called. **`SOAP_PERSISTENCE_SESSION`** - SoapServer data persists between requests. This is accomplished by serializing the SoapServer class data into [$\_SESSION['\_bogus\_session\_name']](reserved.variables.session), because of this [session\_start()](function.session-start) must be called before this persistence mode is set. ### Return Values No value is returned. ### Examples **Example #1 **SoapServer::setPersistence()** example** ``` <?php  class MyFirstPersistentSoapServer {      private $resource; // (Such as PDO, mysqli, etc..)      public $myvar1;      public $myvar2;      public function __construct() {          $this->__wakeup(); // We're calling our wakeup to handle starting our resource      }      public function __wakeup() {          $this->resource = CodeToStartOurResourceUp();      }      public function __sleep() {          // We make sure to leave out $resource here, so our session data remains persistent          // Failure to do so will result in the failure during the unserialization of data          // on the next request; thus, our SoapObject would not be persistent across requests.          return array('myvar1','myvar2');      }  }  try {      session_start();      $server = new SoapServer(null, array('uri' => $_SERVER['REQUEST_URI']));      $server->setClass('MyFirstPersistentSoapServer');      // setPersistence MUST be called after setClass, because setClass's      // behavior sets SESSION_PERSISTENCE_REQUEST upon enacting the method.      $server->setPersistence(SOAP_PERSISTENCE_SESSION);      $server->handle();  } catch(SoapFault $e) {      error_log("SOAP ERROR: ". $e->getMessage());  } ?> ``` ### See Also * [SoapServer::setClass()](soapserver.setclass) - Sets the class which handles SOAP requests
programming_docs
php svn_repos_fs svn\_repos\_fs ============== (PECL svn >= 0.1.0) svn\_repos\_fs — Gets a handle on the filesystem for a repository ### Description ``` svn_repos_fs(resource $repos): resource ``` **Warning**This function is currently not documented; only its argument list is available. Gets a handle on the filesystem for a repository ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php mysqli::$server_info mysqli::$server\_info ===================== mysqli::get\_server\_info ========================= mysqli\_get\_server\_info ========================= (PHP 5, PHP 7, PHP 8) mysqli::$server\_info -- mysqli::get\_server\_info -- mysqli\_get\_server\_info — Returns the version of the MySQL server ### Description Object-oriented style string [$mysqli->server\_info](mysqli.get-server-info); ``` public mysqli::get_server_info(): string ``` Procedural style ``` mysqli_get_server_info(mysqli $mysql): string ``` Returns a string representing the version of the MySQL server that the MySQLi extension is connected to. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values A character string representing the server version. ### Examples **Example #1 $mysqli->server\_info example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print server version */ printf("Server version: %s\n", $mysqli->server_info); /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print server version */ printf("Server version: %s\n", mysqli_get_server_info($link)); /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Server version: 4.1.2-alpha-debug ``` ### See Also * [mysqli\_get\_client\_info()](mysqli.get-client-info) - Get MySQL client info * [mysqli\_get\_client\_version()](mysqli.get-client-version) - Returns the MySQL client version as an integer * [mysqli\_get\_server\_version()](mysqli.get-server-version) - Returns the version of the MySQL server as an integer php ArrayObject::getArrayCopy ArrayObject::getArrayCopy ========================= (PHP 5, PHP 7, PHP 8) ArrayObject::getArrayCopy — Creates a copy of the ArrayObject ### Description ``` public ArrayObject::getArrayCopy(): array ``` Exports the [ArrayObject](class.arrayobject) to an array. ### Parameters This function has no parameters. ### Return Values Returns a copy of the array. When the [ArrayObject](class.arrayobject) refers to an object, an array of the properties of that object will be returned. ### Examples **Example #1 **ArrayObject::getArrayCopy()** example** ``` <?php // Array of available fruits $fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10); $fruitsArrayObject = new ArrayObject($fruits); $fruitsArrayObject['pears'] = 4; // create a copy of the array $copy = $fruitsArrayObject->getArrayCopy(); print_r($copy); ?> ``` The above example will output: ``` Array ( [lemons] => 1 [oranges] => 4 [bananas] => 5 [apples] => 10 [pears] => 4 ) ``` php Yaf_View_Simple::clear Yaf\_View\_Simple::clear ======================== (Yaf >=2.2.0) Yaf\_View\_Simple::clear — Clear Assigned values ### Description ``` public Yaf_View_Simple::clear(string $name = ?): bool ``` clear assigned variable ### Parameters `name` assigned variable name if empty, will clear all assigned variables ### Return Values ### Examples **Example #1 **Yaf\_View\_Simple::clear()**example** ``` <?php class IndexController extends Yaf_Controller_Abstract {     public function indexAction() {         $this->getView()->clear("foo")->clear("bar"); // clear "foo" and "bar"         $this->_view->clear(); //clear all assigned variables     } } ?> ``` ### See Also * [Yaf\_View\_Simple::assignRef()](yaf-view-simple.assignref) - The assignRef purpose * [Yaf\_View\_Interface::assign()](yaf-view-interface.assign) - Assign value to View engine * [Yaf\_View\_Simple::\_\_set()](yaf-view-simple.set) - Set value to engine php GearmanJob::returnCode GearmanJob::returnCode ====================== (PECL gearman >= 0.5.0) GearmanJob::returnCode — Get last return code ### Description ``` public GearmanJob::returnCode(): int ``` Returns the last return code issued by the job server. ### Parameters This function has no parameters. ### Return Values A valid Gearman return code. ### See Also * [GearmanTask::returnCode()](gearmantask.returncode) - Get the last return code php SplHeap::isCorrupted SplHeap::isCorrupted ==================== (PHP 7, PHP 8) SplHeap::isCorrupted — Tells if the heap is in a corrupted state ### Description ``` public SplHeap::isCorrupted(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the heap is corrupted, **`false`** otherwise. php mb_strtoupper mb\_strtoupper ============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) mb\_strtoupper — Make a string uppercase ### Description ``` mb_strtoupper(string $string, ?string $encoding = null): string ``` Returns `string` with all alphabetic characters converted to uppercase. ### Parameters `string` The string being uppercased. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values `string` with all alphabetic characters converted to uppercase. ### Examples **Example #1 **mb\_strtoupper()** example** ``` <?php $str = "Mary Had A Little Lamb and She LOVED It So"; $str = mb_strtoupper($str); echo $str; // Prints MARY HAD A LITTLE LAMB AND SHE LOVED IT SO ?> ``` **Example #2 **mb\_strtoupper()** example with non-Latin UTF-8 text** ``` <?php $str = "Τάχιστη αλώπηξ βαφής ψημένη γη, δρασκελίζει υπέρ νωθρού κυνός"; $str = mb_strtoupper($str, 'UTF-8'); echo $str; // Prints ΤΆΧΙΣΤΗ ΑΛΏΠΗΞ ΒΑΦΉΣ ΨΗΜΈΝΗ ΓΗ, ΔΡΑΣΚΕΛΊΖΕΙ ΥΠΈΡ ΝΩΘΡΟΎ ΚΥΝΌΣ ?> ``` ### Notes By contrast to [strtoupper()](function.strtoupper), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as a-umlaut (ä). For more information about the Unicode properties, please see [» http://www.unicode.org/reports/tr21/](http://www.unicode.org/reports/tr21/). ### See Also * [mb\_strtolower()](function.mb-strtolower) - Make a string lowercase * [mb\_convert\_case()](function.mb-convert-case) - Perform case folding on a string * [strtoupper()](function.strtoupper) - Make a string uppercase php Imagick::setImageTicksPerSecond Imagick::setImageTicksPerSecond =============================== (PECL imagick 2, PECL imagick 3) Imagick::setImageTicksPerSecond — Sets the image ticks-per-second ### Description ``` public Imagick::setImageTicksPerSecond(int $ticks_per_second): bool ``` Adjust the amount of time that a frame of an animated image is displayed for. > > **Note**: > > > For animated GIFs, this function does not change the number of 'image ticks' per second, which is always defined as 100. Instead it adjusts the amount of time that the frame is displayed for to simulate the change in 'ticks per second'. > > For example, for an animated GIF where each frame is displayed for 20 ticks (1/5 of a second) when this method is called on each frame of that image with an argument of `50` the frames are adjusted to be displayed for 40 ticks (2/5 of a second) and the animation will play at half the original speed. > > ### Parameters `ticks_per_second` The duration for which an image should be displayed expressed in ticks per second. ### Return Values Returns **`true`** on success. ### Examples **Example #1 Modify animated Gif with **Imagick::setImageTicksPerSecond()**** ``` <?php // Modify an animated gif so the first half of the gif is played at half the // speed it currently is, and the second half to be played at double the speed // it currently is $imagick = new Imagick(realpath("Test.gif")); $imagick = $imagick->coalesceImages(); $totalFrames = $imagick->getNumberImages(); $frameCount = 0; foreach ($imagick as $frame) {     $imagick->setImageTicksPerSecond(50);          if ($frameCount < ($totalFrames / 2)) {         // Modify the frame to be displayed for twice as long as it currently is         $imagick->setImageTicksPerSecond(50);     } else {         // Modify the frame to be displayed for half as long as it currently is         $imagick->setImageTicksPerSecond(200);     }     $frameCount++; } $imagick = $imagick->deconstructImages(); $imagick->writeImages("/path/to/save/output.gif", true); ?> ``` php SolrDocument::valid SolrDocument::valid =================== (PECL solr >= 0.9.2) SolrDocument::valid — Checks if the current position internally is still valid ### Description ``` public SolrDocument::valid(): bool ``` Checks if the current position internally is still valid. It is used during foreach operations. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success and **`false`** if the current position is no longer valid. php posix_seteuid posix\_seteuid ============== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) posix\_seteuid — Set the effective UID of the current process ### Description ``` posix_seteuid(int $user_id): bool ``` Set the effective user ID of the current process. This is a privileged function and needs appropriate privileges (usually root) on the system to be able to perform this function. ### Parameters `user_id` The user id. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [posix\_geteuid()](function.posix-geteuid) - Return the effective user ID of the current process * [posix\_setuid()](function.posix-setuid) - Set the UID of the current process * [posix\_getuid()](function.posix-getuid) - Return the real user ID of the current process php SyncReaderWriter::readunlock SyncReaderWriter::readunlock ============================ (PECL sync >= 1.0.0) SyncReaderWriter::readunlock — Releases a read lock ### Description ``` public SyncReaderWriter::readunlock(): bool ``` Releases a read lock on a [SyncReaderWriter](class.syncreaderwriter) object. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SyncReaderWriter::readunlock()** example** ``` <?php $readwrite = new SyncReaderWriter("FileCacheLock"); $readwrite->readlock(); /* ... */ $readwrite->readunlock(); ?> ``` ### See Also * [SyncReaderWriter::readlock()](syncreaderwriter.readlock) - Waits for a read lock php timezone_open timezone\_open ============== (PHP 5 >= 5.2.0, PHP 7, PHP 8) timezone\_open — Alias of [DateTimeZone::\_\_construct()](datetimezone.construct) ### Description This function is an alias of: [DateTimeZone::\_\_construct()](datetimezone.construct) php get_required_files get\_required\_files ==================== (PHP 4, PHP 5, PHP 7, PHP 8) get\_required\_files — Alias of [get\_included\_files()](function.get-included-files) ### Description This function is an alias of: [get\_included\_files()](function.get-included-files). php Imagick::setImageScene Imagick::setImageScene ====================== (PECL imagick 2, PECL imagick 3) Imagick::setImageScene — Sets the image scene ### Description ``` public Imagick::setImageScene(int $scene): bool ``` Sets the image scene. ### Parameters `scene` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php SolrQuery::getGroupLimit SolrQuery::getGroupLimit ======================== (PECL solr >= 2.2.0) SolrQuery::getGroupLimit — Returns the group.limit value ### Description ``` public SolrQuery::getGroupLimit(): int ``` Returns the group.limit value ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrQuery::setGroupLimit()](solrquery.setgrouplimit) - Specifies the number of results to return for each group. The server default value is 1 php EvPrepare::__construct EvPrepare::\_\_construct ======================== (PECL ev >= 0.2.0) EvPrepare::\_\_construct — Constructs EvPrepare watcher object ### Description public **EvPrepare::\_\_construct**( string `$callback` , string `$data` = ?, string `$priority` = ?) Constructs EvPrepare watcher object. And starts the watcher automatically. If need a stopped watcher consider using [EvPrepare::createStopped()](evprepare.createstopped) ### Parameters `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### See Also * [EvCheck](class.evcheck) php Iterator::key Iterator::key ============= (PHP 5, PHP 7, PHP 8) Iterator::key — Return the key of the current element ### Description ``` public Iterator::key(): mixed ``` Returns the key of the current element. ### Parameters This function has no parameters. ### Return Values Returns scalar on success, or **`null`** on failure. ### Errors/Exceptions Issues **`E_NOTICE`** on failure. php apcu_cas apcu\_cas ========= (PECL apcu >= 4.0.0) apcu\_cas — Updates an old value with a new value ### Description ``` apcu_cas(string $key, int $old, int $new): bool ``` **apcu\_cas()** updates an already existing integer value if the `old` parameter matches the currently stored value with the value of the `new` parameter. ### Parameters `key` The key of the value being updated. `old` The old value (the value currently stored). `new` The new value to update to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **apcu\_cas()** example** ``` <?php apcu_store('foobar', 2); echo '$foobar = 2', PHP_EOL; echo '$foobar == 1 ? 2 : 1 = ', (apcu_cas('foobar', 1, 2) ? 'ok' : 'fail'), PHP_EOL; echo '$foobar == 2 ? 1 : 2 = ', (apcu_cas('foobar', 2, 1) ? 'ok' : 'fail'), PHP_EOL; echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL; echo '$f__bar == 1 ? 2 : 1 = ', (apcu_cas('f__bar', 1, 2) ? 'ok' : 'fail'), PHP_EOL; apcu_store('perfection', 'xyz'); echo '$perfection == 2 ? 1 : 2 = ', (apcu_cas('perfection', 2, 1) ? 'ok' : 'epic fail'), PHP_EOL; echo '$foobar = ', apcu_fetch('foobar'), PHP_EOL; ?> ``` The above example will output something similar to: ``` $foobar = 2 $foobar == 1 ? 2 : 1 = fail $foobar == 2 ? 1 : 2 = ok $foobar = 1 $f__bar == 1 ? 2 : 1 = fail $perfection == 2 ? 1 : 2 = epic fail $foobar = 1 ``` ### See Also * [apcu\_dec()](function.apcu-dec) - Decrease a stored number * [apcu\_store()](function.apcu-store) - Cache a variable in the data store php ReflectionGenerator::getExecutingFile ReflectionGenerator::getExecutingFile ===================================== (PHP 7, PHP 8) ReflectionGenerator::getExecutingFile — Gets the file name of the currently executing generator ### Description ``` public ReflectionGenerator::getExecutingFile(): string ``` Get the full path and file name of the currently executing generator. ### Parameters This function has no parameters. ### Return Values Returns the full path and file name of the currently executing generator. ### Examples **Example #1 **ReflectionGenerator::getExecutingFile()** example** ``` <?php class GenExample {     public function gen()     {         yield 1;     } } $gen = (new GenExample)->gen(); $reflectionGen = new ReflectionGenerator($gen); echo "File: {$reflectionGen->getExecutingFile()}"; ``` The above example will output something similar to: ``` File: /path/to/file/example.php ``` ### See Also * [ReflectionGenerator::getExecutingLine()](reflectiongenerator.getexecutingline) - Gets the currently executing line of the generator * [ReflectionGenerator::getExecutingGenerator()](reflectiongenerator.getexecutinggenerator) - Gets the executing Generator object php tidyNode::hasChildren tidyNode::hasChildren ===================== (PHP 5, PHP 7, PHP 8) tidyNode::hasChildren — Checks if a node has children ### Description ``` public tidyNode::hasChildren(): bool ``` Tells if the node has children. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the node has children, **`false`** otherwise. ### Examples **Example #1 **tidyNode::hasChildren()** example** ``` <?php $html = <<< HTML <html><head> <?php echo '<title>title</title>'; ?> <#    /* JSTE code */   alert('Hello World');  #> </head> <body> <?php   // PHP code   echo 'hello world!'; ?> <%   /* ASP code */   response.write("Hello World!") %> <!-- Comments --> Hello World </body></html> Outside HTML HTML; $tidy = tidy_parse_string($html); $num = 0; // the head tag var_dump($tidy->html()->child[0]->hasChildren()); // the php inside the head tag var_dump($tidy->html()->child[0]->child[0]->hasChildren()); ?> ``` The above example will output: ``` bool(true) bool(false) ``` php ReflectionClass::getConstant ReflectionClass::getConstant ============================ (PHP 5, PHP 7, PHP 8) ReflectionClass::getConstant — Gets defined constant ### Description ``` public ReflectionClass::getConstant(string $name): mixed ``` Gets the defined constant. ### Parameters `name` The name of the class constant to get. ### Return Values Value of the constant with the name `name`. Returns **`false`** if the constant was not found in the class. ### Examples **Example #1 Usage of **ReflectionClass::getConstant()**** ``` <?php class Example {     const C1 = false;     const C2 = 'I am a constant'; } $reflection = new ReflectionClass('Example'); var_dump($reflection->getConstant('C1')); var_dump($reflection->getConstant('C2')); var_dump($reflection->getConstant('C3')); ?> ``` The above example will output: ``` bool(false) string(15) "I am a constant" bool(false) ``` ### See Also * [ReflectionClass::getConstants()](reflectionclass.getconstants) - Gets constants php EventBase::free EventBase::free =============== (PECL event >= 1.10.0) EventBase::free — Free resources allocated for this event base ### Description ``` public EventBase::free(): void ``` Deallocates resources allocated by libevent for the [EventBase](class.eventbase) object. **Warning** The **EventBase::free()** method doesn't destruct the object itself. To destruct the object completely call [unset()](function.unset) , or assign **`null`**. This method does not deallocate or detach any of the events that are currently associated with the [EventBase](class.eventbase) object, or close any of their sockets - beware. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EventBase::\_\_construct()](eventbase.construct) - Constructs EventBase object
programming_docs
php mb_strimwidth mb\_strimwidth ============== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_strimwidth — Get truncated string with specified width ### Description ``` mb_strimwidth( string $string, int $start, int $width, string $trim_marker = "", ?string $encoding = null ): string ``` Truncates string `string` to specified `width`, where halfwidth characters count as `1`, and fullwidth characters count as `2`. See [» http://www.unicode.org/reports/tr11/](http://www.unicode.org/reports/tr11/) for details regarding East Asian character widths. ### Parameters `string` The string being decoded. `start` The start position offset. Number of characters from the beginning of string (first character is 0), or if start is negative, number of characters from the end of the string. `width` The width of the desired trim. Negative widths count from the end of the string. `trim_marker` A string that is added to the end of string when string is truncated. `encoding` The `encoding` parameter is the character encoding. If it is omitted or **`null`**, the internal character encoding value will be used. ### Return Values The truncated string. If `trim_marker` is set, `trim_marker` replaces the last chars to match the `width`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `encoding` is nullable now. | | 7.1.0 | Support for negative `start`s and `width`s has been added. | ### Examples **Example #1 **mb\_strimwidth()** example** ``` <?php echo mb_strimwidth("Hello World", 0, 10, "..."); // output: "Hello W..." ?> ``` ### See Also * [mb\_strwidth()](function.mb-strwidth) - Return width of string * [mb\_internal\_encoding()](function.mb-internal-encoding) - Set/Get internal character encoding php Ds\Deque::capacity Ds\Deque::capacity ================== (PECL ds >= 1.0.0) Ds\Deque::capacity — Returns the current capacity ### Description ``` public Ds\Deque::capacity(): int ``` Returns the current capacity. ### Parameters This function has no parameters. ### Return Values The current capacity. ### Examples **Example #1 **Ds\Deque::capacity()** example** ``` <?php $deque = new \Ds\Deque(); var_dump($deque->capacity()); $deque->push(...range(1, 50)); var_dump($deque->capacity()); ?> ``` The above example will output something similar to: ``` int(8) int(64) ``` php The SessionHandlerInterface class The SessionHandlerInterface class ================================= Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8) **SessionHandlerInterface** is an interface which defines the minimal prototype for creating a custom session handler. In order to pass a custom session handler to [session\_set\_save\_handler()](function.session-set-save-handler) using its OOP invocation, the class can implement this interface. Please note the callback methods of this class are designed to be called internally by PHP and are not meant to be called from user-space code. Interface synopsis ------------------ interface **SessionHandlerInterface** { /\* Methods \*/ ``` public close(): bool ``` ``` public destroy(string $id): bool ``` ``` public gc(int $max_lifetime): int|false ``` ``` public open(string $path, string $name): bool ``` ``` public read(string $id): string|false ``` ``` public write(string $id, string $data): bool ``` } **Example #1 Example using **SessionHandlerInterface**** The following example provides file based session storage similar to the PHP sessions default save handler `files`. This example could easily be extended to cover database storage using your favorite PHP supported database engine. Note we use the OOP prototype with [session\_set\_save\_handler()](function.session-set-save-handler) and register the shutdown function using the function's parameter flag. This is generally advised when registering objects as session save handlers. **Caution** For brevity, this example omits input validation. However, the `$id` parameters are actually user supplied values which require proper validation/sanitization to avoid vulnerabilities, such as path traversal issues. *So do not use this example unmodified in production environments.* ``` <?php class MySessionHandler implements SessionHandlerInterface {     private $savePath;     public function open($savePath, $sessionName): bool     {         $this->savePath = $savePath;         if (!is_dir($this->savePath)) {             mkdir($this->savePath, 0777);         }         return true;     }     public function close(): bool     {         return true;     }     #[ReturnTypeWillChange]     public function read($id)     {         return (string)@file_get_contents("$this->savePath/sess_$id");     }     public function write($id, $data): bool     {         return file_put_contents("$this->savePath/sess_$id", $data) === false ? false : true;     }     public function destroy($id): bool     {         $file = "$this->savePath/sess_$id";         if (file_exists($file)) {             unlink($file);         }         return true;     }     #[ReturnTypeWillChange]     public function gc($maxlifetime)     {         foreach (glob("$this->savePath/sess_*") as $file) {             if (filemtime($file) + $maxlifetime < time() && file_exists($file)) {                 unlink($file);             }         }         return true;     } } $handler = new MySessionHandler(); session_set_save_handler($handler, true); session_start(); // proceed to set and retrieve values by key from $_SESSION ``` Table of Contents ----------------- * [SessionHandlerInterface::close](sessionhandlerinterface.close) — Close the session * [SessionHandlerInterface::destroy](sessionhandlerinterface.destroy) — Destroy a session * [SessionHandlerInterface::gc](sessionhandlerinterface.gc) — Cleanup old sessions * [SessionHandlerInterface::open](sessionhandlerinterface.open) — Initialize session * [SessionHandlerInterface::read](sessionhandlerinterface.read) — Read session data * [SessionHandlerInterface::write](sessionhandlerinterface.write) — Write session data php mcrypt_module_get_algo_key_size mcrypt\_module\_get\_algo\_key\_size ==================================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_module\_get\_algo\_key\_size — Returns the maximum supported keysize of the opened mode **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_module_get_algo_key_size(string $algorithm, string $lib_dir = ?): int ``` Gets the maximum supported keysize of the opened mode. ### Parameters `algorithm` The algorithm name. `lib_dir` This optional parameter can contain the location where the mode module is on the system. ### Return Values This function returns the maximum supported key size of the algorithm specified in bytes. php mysqli::$error_list mysqli::$error\_list ==================== mysqli\_error\_list =================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) mysqli::$error\_list -- mysqli\_error\_list — Returns a list of errors from the last command executed ### Description Object-oriented style array [$mysqli->error\_list](mysqli.error-list); Procedural style ``` mysqli_error_list(mysqli $mysql): array ``` Returns a array of errors for the most recent MySQLi function call that can succeed or fail. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values A list of errors, each as an associative array containing the errno, error, and sqlstate. ### Examples **Example #1 $mysqli->error\_list example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "nobody", ""); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } if (!$mysqli->query("SET a=1")) {     print_r($mysqli->error_list); } /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } if (!mysqli_query($link, "SET a=1")) {     print_r(mysqli_error_list($link)); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Array ( [0] => Array ( [errno] => 1193 [sqlstate] => HY000 [error] => Unknown system variable 'a' ) ) ``` ### See Also * [mysqli\_connect\_errno()](mysqli.connect-errno) - Returns the error code from last connect call * [mysqli\_connect\_error()](mysqli.connect-error) - Returns a description of the last connection error * [mysqli\_error()](mysqli.error) - Returns a string description of the last error * [mysqli\_sqlstate()](mysqli.sqlstate) - Returns the SQLSTATE error from previous MySQL operation php stats_dens_t stats\_dens\_t ============== (PECL stats >= 1.0.0) stats\_dens\_t — Probability density function of the t-distribution ### Description ``` stats_dens_t(float $x, float $dfr): float ``` Returns the probability density at `x`, where the random variable follows the t-distribution of which the degree of freedom is `dfr`. ### Parameters `x` The value at which the probability density is calculated `dfr` The degree of freedom of the distribution ### Return Values The probability density at `x` or **`false`** for failure. php sem_acquire sem\_acquire ============ (PHP 4, PHP 5, PHP 7, PHP 8) sem\_acquire — Acquire a semaphore ### Description ``` sem_acquire(SysvSemaphore $semaphore, bool $non_blocking = false): bool ``` **sem\_acquire()** by default blocks (if necessary) until the semaphore can be acquired. A process attempting to acquire a semaphore which it has already acquired will block forever if acquiring the semaphore would cause its maximum number of semaphore to be exceeded. After processing a request, any semaphores acquired by the process but not explicitly released will be released automatically and a warning will be generated. ### Parameters `semaphore` `semaphore` is a semaphore obtained from [sem\_get()](function.sem-get). `non_blocking` Specifies if the process shouldn't wait for the semaphore to be acquired. If set to `true`, the call will return `false` immediately if a semaphore cannot be immediately acquired. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `semaphore` expects a [SysvSemaphore](class.sysvsemaphore) instance now; previously, a resource was expected. | ### See Also * [sem\_get()](function.sem-get) - Get a semaphore id * [sem\_release()](function.sem-release) - Release a semaphore php curl_share_setopt curl\_share\_setopt =================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) curl\_share\_setopt — Set an option for a cURL share handle ### Description ``` curl_share_setopt(CurlShareHandle $share_handle, int $option, mixed $value): bool ``` Sets an option on the given cURL share handle. ### Parameters `share_handle` A cURL share handle returned by [curl\_share\_init()](function.curl-share-init). `option` | Option | Description | | --- | --- | | **`CURLSHOPT_SHARE`** | Specifies a type of data that should be shared. | | **`CURLSHOPT_UNSHARE`** | Specifies a type of data that will be no longer shared. | `value` | Value | Description | | --- | --- | | **`CURL_LOCK_DATA_COOKIE`** | Shares cookie data. | | **`CURL_LOCK_DATA_DNS`** | Shares DNS cache. Note that when you use cURL multi handles, all handles added to the same multi handle will share DNS cache by default. | | **`CURL_LOCK_DATA_SSL_SESSION`** | Shares SSL session IDs, reducing the time spent on the SSL handshake when reconnecting to the same server. Note that SSL session IDs are reused within the same handle by default. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `share_handle` expects a [CurlShareHandle](class.curlsharehandle) instance now; previously, a resource was expected. | ### Examples **Example #1 **curl\_share\_setopt()** example** This example will create a cURL share handle, add two cURL handles to it, and then run them with cookie data sharing. ``` <?php // Create cURL share handle and set it to share cookie data $sh = curl_share_init(); curl_share_setopt($sh, CURLSHOPT_SHARE, CURL_LOCK_DATA_COOKIE); // Initialize the first cURL handle and assign the share handle to it $ch1 = curl_init("http://example.com/"); curl_setopt($ch1, CURLOPT_SHARE, $sh); // Execute the first cURL handle curl_exec($ch1); // Initialize the second cURL handle and assign the share handle to it $ch2 = curl_init("http://php.net/"); curl_setopt($ch2, CURLOPT_SHARE, $sh); // Execute the second cURL handle //  all cookies from $ch1 handle are shared with $ch2 handle curl_exec($ch2); // Close the cURL share handle curl_share_close($sh); // Close the cURL handles curl_close($ch1); curl_close($ch2); ?> ``` php uopz_flags uopz\_flags =========== (PECL uopz 2 >= 2.0.2, PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_flags — Get or set flags on function or class ### Description ``` uopz_flags(string $function, int $flags = PHP_INT_MAX): int ``` ``` uopz_flags(string $class, string $function, int $flags = PHP_INT_MAX): int ``` Get or set the flags on a class or function entry at runtime ### Parameters `class` The name of a class `function` The name of the function. If `class` is given and an empty string is passed as `function`, **uopz\_flags()** gets or sets the flags of the class entry. `flags` A valid set of ZEND\_ACC\_ flags. If omitted, **uopz\_flags()** acts as getter. ### Return Values If setting, returns old flags, else returns flags ### Errors/Exceptions As of PHP 7.4.0, if the parameter `flags` is passed, **uopz\_flags()** throws a [RuntimeException](class.runtimeexception), if [OPcache](https://www.php.net/manual/en/book.opcache.php) is enabled, and the class entry of `class` or the function entry of `function` is immutable. ### Changelog | Version | Description | | --- | --- | | PECL uopz 5.0.0 | The `flags` parameter is now optional. Formerly, **`ZEND_ACC_FETCH`** had to be passed to use **uopz\_flags()** as getter. | ### Examples **Example #1 **uopz\_flags()** example** ``` <?php class Test {     public function method() {         return __CLASS__;     } } $flags = uopz_flags("Test", "method"); var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE)); var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC)); var_dump(uopz_flags("Test", "method", $flags|ZEND_ACC_STATIC|ZEND_ACC_PRIVATE)); var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_PRIVATE)); var_dump((bool) (uopz_flags("Test", "method") & ZEND_ACC_STATIC)); ?> ``` The above example will output: ``` bool(false) bool(false) int(1234567890) bool(true) bool(true) ``` **Example #2 "Unfinalize" a Class** ``` <?php final class MyClass { } $flags = uopz_flags(MyClass::class, ''); uopz_flags(MyClass::class, '', $flags & ~ZEND_ACC_FINAL); var_dump((new ReflectionClass(MyClass::class))->isFinal()); ?> ``` The above example will output: ``` bool(false) ``` php gnupg_sign gnupg\_sign =========== (PECL gnupg >= 0.1) gnupg\_sign — Signs a given text ### Description ``` gnupg_sign(resource $identifier, string $plaintext): string ``` Signs the given `plaintext` with the keys, which were set with [gnupg\_addsignkey](function.gnupg-addsignkey) before and returns the signed text or the signature, depending on what was set with [gnupg\_setsignmode](function.gnupg-setsignmode). ### Parameters `identifier` The gnupg identifier, from a call to [gnupg\_init()](function.gnupg-init) or **gnupg**. `plaintext` The plain text being signed. ### Return Values On success, this function returns the signed text or the signature. On failure, this function returns **`false`**. ### Examples **Example #1 Procedural **gnupg\_sign()** example** ``` <?php $res = gnupg_init(); gnupg_addsignkey($res,"8660281B6051D071D94B5B230549F9DC851566DC","test"); $signed = gnupg_sign($res, "just a test"); echo $signed; ?> ``` **Example #2 OO **gnupg\_sign()** example** ``` <?php $gpg = new gnupg(); $gpg->addsignkey("8660281B6051D071D94B5B230549F9DC851566DC","test"); $signed = $gpg->sign("just a test"); echo $signed; ?> ``` php SolrResponse::getRawResponseHeaders SolrResponse::getRawResponseHeaders =================================== (PECL solr >= 0.9.2) SolrResponse::getRawResponseHeaders — Returns the raw response headers from the server ### Description ``` public SolrResponse::getRawResponseHeaders(): string ``` Returns the raw response headers from the server. ### Parameters This function has no parameters. ### Return Values Returns the raw response headers from the server. php ReflectionEnum::getCase ReflectionEnum::getCase ======================= (PHP 8 >= 8.1.0) ReflectionEnum::getCase — Returns a specific case of an Enum ### Description ``` public ReflectionEnum::getCase(string $name): ReflectionEnumUnitCase ``` Returns the reflection object for a specific Enum case by name. If the requested case is not defined, a [ReflectionException](class.reflectionexception) is thrown. ### Parameters `name` The name of the case to retrieve. ### Return Values An instance of [ReflectionEnumUnitCase](class.reflectionenumunitcase) or [ReflectionEnumBackedCase](class.reflectionenumbackedcase), as appropriate. ### Examples **Example #1 **ReflectionEnum::getCase()** example** ``` <?php enum Suit {     case Hearts;     case Diamonds;     case Clubs;     case Spades; } $rEnum = new ReflectionEnum(Suit::class); $rCase = $rEnum->getCase('Clubs'); var_dump($rCase->getValue()); ?> ``` The above example will output: ``` enum(Suit::Clubs) ``` ### See Also * [Enumerations](https://www.php.net/manual/en/language.enumerations.php) * [ReflectionEnum::getCases()](reflectionenum.getcases) - Returns a list of all cases on an Enum * [ReflectionEnum::hasCase()](reflectionenum.hascase) - Checks for a case on an Enum * [ReflectionEnum::isBacked()](reflectionenum.isbacked) - Determines if an Enum is a Backed Enum php ReflectionExtension::getClasses ReflectionExtension::getClasses =============================== (PHP 5, PHP 7, PHP 8) ReflectionExtension::getClasses — Gets classes ### Description ``` public ReflectionExtension::getClasses(): array ``` Gets a list of classes from an extension. ### Parameters This function has no parameters. ### Return Values An array of [ReflectionClass](class.reflectionclass) objects, one for each class within the extension. If no classes are defined, an empty array is returned. ### Examples **Example #1 **ReflectionExtension::getClasses()** example** ``` <?php $ext = new ReflectionExtension('XMLWriter'); var_dump($ext->getClasses()); ?> ``` The above example will output something similar to: ``` array(1) { ["XMLWriter"]=> object(ReflectionClass)#2 (1) { ["name"]=> string(9) "XMLWriter" } } ``` ### See Also * [ReflectionExtension::getClassNames()](reflectionextension.getclassnames) - Gets class names
programming_docs
php filter_has_var filter\_has\_var ================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) filter\_has\_var — Checks if variable of specified type exists ### Description ``` filter_has_var(int $input_type, string $var_name): bool ``` ### Parameters `input_type` One of **`INPUT_GET`**, **`INPUT_POST`**, **`INPUT_COOKIE`**, **`INPUT_SERVER`**, or **`INPUT_ENV`**. `var_name` Name of a variable to check. ### Return Values Returns **`true`** on success or **`false`** on failure. php stats_rand_setall stats\_rand\_setall =================== (PECL stats >= 1.0.0) stats\_rand\_setall — Set seed values to the random generator ### Description ``` stats_rand_setall(int $iseed1, int $iseed2): void ``` Set `iseed1` and `iseed2` as seed values to the random generator used in statistic functions. ### Parameters `iseed1` The value which is used as the random seed `iseed2` The value which is used as the random seed ### Return Values No values are returned. php MultipleIterator::detachIterator MultipleIterator::detachIterator ================================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) MultipleIterator::detachIterator — Detaches an iterator ### Description ``` public MultipleIterator::detachIterator(Iterator $iterator): void ``` Detaches an iterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `iterator` The iterator to detach. ### Return Values No value is returned. ### See Also * [MultipleIterator::attachIterator()](multipleiterator.attachiterator) - Attaches iterator information php ReflectionParameter::__clone ReflectionParameter::\_\_clone ============================== (PHP 5, PHP 7, PHP 8) ReflectionParameter::\_\_clone — Clone ### Description ``` private ReflectionParameter::__clone(): void ``` Clones. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This method is no longer final. | ### See Also * **ReflectionParameter::toString()** * [Object cloning](language.oop5.cloning) php pcntl_wtermsig pcntl\_wtermsig =============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_wtermsig — Returns the signal which caused the child to terminate ### Description ``` pcntl_wtermsig(int $status): int|false ``` Returns the number of the signal that caused the child process to terminate. This function is only useful if [pcntl\_wifsignaled()](function.pcntl-wifsignaled) returned **`true`**. ### Parameters `status` The `status` parameter is the status parameter supplied to a successful call to [pcntl\_waitpid()](function.pcntl-waitpid). ### Return Values Returns the signal number. If the functionality is not supported by the OS, **`false`** is returned. ### See Also * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child * [pcntl\_signal()](function.pcntl-signal) - Installs a signal handler * [pcntl\_wifsignaled()](function.pcntl-wifsignaled) - Checks whether the status code represents a termination due to a signal php ImagickPixel::getColorValue ImagickPixel::getColorValue =========================== (PECL imagick 2, PECL imagick 3) ImagickPixel::getColorValue — Gets the normalized value of the provided color channel ### Description ``` public ImagickPixel::getColorValue(int $color): float ``` Retrieves the value of the color channel specified, as a floating-point number between 0 and 1. ### Parameters `color` The color to get the value of, specified as one of the Imagick color constants. This can be one of the RGB colors, CMYK colors, alpha and opacity e.g (Imagick::COLOR\_BLUE, Imagick::COLOR\_MAGENTA). ### Return Values The value of the channel, as a normalized floating-point number, throwing ImagickPixelException on error. ### Examples **Example #1 Basic **Imagick::getColorValue()** usage** ``` <?php      $color = new ImagickPixel('rgba(90%, 20%, 20%, 0.75)'); echo "Alpha value is ".$color->getColorValue(Imagick::COLOR_ALPHA).PHP_EOL; echo "".PHP_EOL; echo "Red value is ".$color->getColorValue(Imagick::COLOR_RED).PHP_EOL; echo "Green value is ".$color->getColorValue(Imagick::COLOR_GREEN).PHP_EOL; echo "Blue value is ".$color->getColorValue(Imagick::COLOR_BLUE).PHP_EOL; echo "".PHP_EOL; echo "Cyan value is ".$color->getColorValue(Imagick::COLOR_CYAN).PHP_EOL; echo "Magenta value is ".$color->getColorValue(Imagick::COLOR_MAGENTA).PHP_EOL; echo "Yellow value is ".$color->getColorValue(Imagick::COLOR_YELLOW).PHP_EOL; echo "Black value is ".$color->getColorValue(Imagick::COLOR_BLACK).PHP_EOL; ?> ``` The above example will output: ``` Alpha value is 0.74999618524453 Red value is 0.90000762951095 Green value is 0.2 Blue value is 0.2 Cyan value is 0.90000762951095 Magenta value is 0.2 Yellow value is 0.2 Black value is 0 ``` php The ArrayIterator class The ArrayIterator class ======================= Introduction ------------ (PHP 5, PHP 7, PHP 8) This iterator allows to unset and modify values and keys while iterating over Arrays and Objects. When you want to iterate over the same array multiple times you need to instantiate ArrayObject and let it create ArrayIterator instances that refer to it either by using [foreach](control-structures.foreach) or by calling its getIterator() method manually. Class synopsis -------------- class **ArrayIterator** implements [SeekableIterator](class.seekableiterator), [ArrayAccess](class.arrayaccess), [Serializable](class.serializable), [Countable](class.countable) { /\* Constants \*/ public const int [STD\_PROP\_LIST](class.arrayiterator#arrayiterator.constants.std-prop-list); public const int [ARRAY\_AS\_PROPS](class.arrayiterator#arrayiterator.constants.array-as-props); /\* Methods \*/ public [\_\_construct](arrayiterator.construct)(array|object `$array` = [], int `$flags` = 0) ``` public append(mixed $value): void ``` ``` public asort(int $flags = SORT_REGULAR): bool ``` ``` public count(): int ``` ``` public current(): mixed ``` ``` public getArrayCopy(): array ``` ``` public getFlags(): int ``` ``` public key(): string|int|null ``` ``` public ksort(int $flags = SORT_REGULAR): bool ``` ``` public natcasesort(): bool ``` ``` public natsort(): bool ``` ``` public next(): void ``` ``` public offsetExists(mixed $key): bool ``` ``` public offsetGet(mixed $key): mixed ``` ``` public offsetSet(mixed $key, mixed $value): void ``` ``` public offsetUnset(mixed $key): void ``` ``` public rewind(): void ``` ``` public seek(int $offset): void ``` ``` public serialize(): string ``` ``` public setFlags(int $flags): void ``` ``` public uasort(callable $callback): bool ``` ``` public uksort(callable $callback): bool ``` ``` public unserialize(string $data): void ``` ``` public valid(): bool ``` } Predefined Constants -------------------- ArrayIterator Flags ------------------- **`ArrayIterator::STD_PROP_LIST`** Properties of the object have their normal functionality when accessed as list (var\_dump, foreach, etc.). **`ArrayIterator::ARRAY_AS_PROPS`** Entries can be accessed as properties (read and write). Table of Contents ----------------- * [ArrayIterator::append](arrayiterator.append) — Append an element * [ArrayIterator::asort](arrayiterator.asort) — Sort entries by values * [ArrayIterator::\_\_construct](arrayiterator.construct) — Construct an ArrayIterator * [ArrayIterator::count](arrayiterator.count) — Count elements * [ArrayIterator::current](arrayiterator.current) — Return current array entry * [ArrayIterator::getArrayCopy](arrayiterator.getarraycopy) — Get array copy * [ArrayIterator::getFlags](arrayiterator.getflags) — Get behavior flags * [ArrayIterator::key](arrayiterator.key) — Return current array key * [ArrayIterator::ksort](arrayiterator.ksort) — Sort entries by keys * [ArrayIterator::natcasesort](arrayiterator.natcasesort) — Sort entries naturally, case insensitive * [ArrayIterator::natsort](arrayiterator.natsort) — Sort entries naturally * [ArrayIterator::next](arrayiterator.next) — Move to next entry * [ArrayIterator::offsetExists](arrayiterator.offsetexists) — Check if offset exists * [ArrayIterator::offsetGet](arrayiterator.offsetget) — Get value for an offset * [ArrayIterator::offsetSet](arrayiterator.offsetset) — Set value for an offset * [ArrayIterator::offsetUnset](arrayiterator.offsetunset) — Unset value for an offset * [ArrayIterator::rewind](arrayiterator.rewind) — Rewind array back to the start * [ArrayIterator::seek](arrayiterator.seek) — Seek to position * [ArrayIterator::serialize](arrayiterator.serialize) — Serialize * [ArrayIterator::setFlags](arrayiterator.setflags) — Set behaviour flags * [ArrayIterator::uasort](arrayiterator.uasort) — Sort with a user-defined comparison function and maintain index association * [ArrayIterator::uksort](arrayiterator.uksort) — Sort by keys using a user-defined comparison function * [ArrayIterator::unserialize](arrayiterator.unserialize) — Unserialize * [ArrayIterator::valid](arrayiterator.valid) — Check whether array contains more entries php None Magic constants --------------- There are nine magical constants that change depending on where they are used. For example, the value of **`__LINE__`** depends on the line that it's used on in your script. All these "magical" constants are resolved at compile time, unlike regular constants, which are resolved at runtime. These special constants are case-insensitive and are as follows: **PHP's magic constants**| Name | Description | | --- | --- | | **`__LINE__`** | The current line number of the file. | | **`__FILE__`** | The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned. | | **`__DIR__`** | The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to `dirname(__FILE__)`. This directory name does not have a trailing slash unless it is the root directory. | | **`__FUNCTION__`** | The function name, or `{closure}` for anonymous functions. | | **`__CLASS__`** | The class name. The class name includes the namespace it was declared in (e.g. `Foo\Bar`). When used in a trait method, \_\_CLASS\_\_ is the name of the class the trait is used in. | | **`__TRAIT__`** | The trait name. The trait name includes the namespace it was declared in (e.g. `Foo\Bar`). | | **`__METHOD__`** | The class method name. | | **`__NAMESPACE__`** | The name of the current namespace. | | **`ClassName::class`** | The fully qualified class name. | ### See Also * [::class](language.oop5.basic#language.oop5.basic.class.class) * [get\_class()](function.get-class) * [get\_object\_vars()](function.get-object-vars) * [file\_exists()](function.file-exists) * [function\_exists()](function.function-exists) php Gmagick::setimageredprimary Gmagick::setimageredprimary =========================== (PECL gmagick >= Unknown) Gmagick::setimageredprimary — Sets the image chromaticity red primary point ### Description ``` public Gmagick::setimageredprimary(float $x, float $y): Gmagick ``` Sets the image chromaticity red primary point. ### Parameters `x` The red primary x-point. `y` The red primary y-point. ### Return Values The Gmagick object on success. ### Errors/Exceptions Throws an **GmagickException** on error. php exif_read_data exif\_read\_data ================ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) exif\_read\_data — Reads the EXIF headers from an image file ### Description ``` exif_read_data( resource|string $file, ?string $required_sections = null, bool $as_arrays = false, bool $read_thumbnail = false ): array|false ``` **exif\_read\_data()** reads the EXIF headers from an image file. This way you can read meta data generated by digital cameras. EXIF headers tend to be present in JPEG/TIFF images generated by digital cameras, but unfortunately each digital camera maker has a different idea of how to actually tag their images, so you can't always rely on a specific Exif header being present. `Height` and `Width` are computed the same way [getimagesize()](function.getimagesize) does so their values must not be part of any header returned. Also, `html` is a height/width text string to be used inside normal HTML. When an Exif header contains a Copyright note, this itself can contain two values. As the solution is inconsistent in the Exif 2.10 standard, the `COMPUTED` section will return both entries `Copyright.Photographer` and `Copyright.Editor` while the `IFD0` sections contains the byte array with the NULL character that splits both entries. Or just the first entry if the datatype was wrong (normal behaviour of Exif). The `COMPUTED` will also contain the entry `Copyright` which is either the original copyright string, or a comma separated list of the photo and editor copyright. The tag `UserComment` has the same problem as the Copyright tag. It can store two values. First the encoding used, and second the value itself. If so the `IFD` section only contains the encoding or a byte array. The `COMPUTED` section will store both in the entries `UserCommentEncoding` and `UserComment`. The entry `UserComment` is available in both cases so it should be used in preference to the value in `IFD0` section. **exif\_read\_data()** also validates EXIF data tags according to the EXIF specification ([» http://exif.org/Exif2-2.PDF](http://exif.org/Exif2-2.PDF), page 20). ### Parameters `file` The location of the image file. This can either be a path to the file (stream wrappers are also supported as usual) or a stream resource. `required_sections` Is a comma separated list of sections that need to be present in file to produce a result array. If none of the requested sections could be found the return value is **`false`**. | | | | --- | --- | | FILE | FileName, FileSize, FileDateTime, SectionsFound | | COMPUTED | html, Width, Height, IsColor, and more if available. Height and Width are computed the same way [getimagesize()](function.getimagesize) does so their values must not be part of any header returned. Also, `html` is a height/width text string to be used inside normal HTML. | | ANY\_TAG | Any information that has a Tag e.g. `IFD0`, `EXIF`, ... | | IFD0 | All tagged data of IFD0. In normal imagefiles this contains image size and so forth. | | THUMBNAIL | A file is supposed to contain a thumbnail if it has a second `IFD`. All tagged information about the embedded thumbnail is stored in this section. | | COMMENT | Comment headers of JPEG images. | | EXIF | The EXIF section is a sub section of `IFD0`. It contains more detailed information about an image. Most of these entries are digital camera related. | `as_arrays` Specifies whether or not each section becomes an array. The `required_sections` `COMPUTED`, `THUMBNAIL`, and `COMMENT` always become arrays as they may contain values whose names conflict with other sections. `read_thumbnail` When set to **`true`** the thumbnail itself is read. Otherwise, only the tagged data is read. ### Return Values It returns an associative array where the array indexes are the header names and the array values are the values associated with those headers. If no data can be returned, **exif\_read\_data()** will return **`false`**. ### Errors/Exceptions Errors of level **`E_WARNING`** and/or **`E_NOTICE`** may be raised for unsupported tags or other potential error conditions, but the function still tries to read all comprehensible information. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `required_sections` is nullable now. | | 7.2.0 | The `file` parameter now supports both local files and stream resources. | | 7.2.0 | Support for the following EXIF formats were added: * Samsung * DJI * Panasonic * Sony * Pentax * Minolta * Sigma/Foveon * AGFA * Kyocera * Ricoh * Epson | ### Examples **Example #1 **exif\_read\_data()** example** ``` <?php echo "test1.jpg:<br />\n"; $exif = exif_read_data('tests/test1.jpg', 'IFD0'); echo $exif===false ? "No header data found.<br />\n" : "Image contains headers<br />\n"; $exif = exif_read_data('tests/test2.jpg', 0, true); echo "test2.jpg:<br />\n"; foreach ($exif as $key => $section) {     foreach ($section as $name => $val) {         echo "$key.$name: $val<br />\n";     } } ?> ``` The first call fails because the image has no header information. The above example will output something similar to: ``` test1.jpg: No header data found. test2.jpg: FILE.FileName: test2.jpg FILE.FileDateTime: 1017666176 FILE.FileSize: 1240 FILE.FileType: 2 FILE.SectionsFound: ANY_TAG, IFD0, THUMBNAIL, COMMENT COMPUTED.html: width="1" height="1" COMPUTED.Height: 1 COMPUTED.Width: 1 COMPUTED.IsColor: 1 COMPUTED.ByteOrderMotorola: 1 COMPUTED.UserComment: Exif test image. COMPUTED.UserCommentEncoding: ASCII COMPUTED.Copyright: Photo (c) M.Boerger, Edited by M.Boerger. COMPUTED.Copyright.Photographer: Photo (c) M.Boerger COMPUTED.Copyright.Editor: Edited by M.Boerger. IFD0.Copyright: Photo (c) M.Boerger IFD0.UserComment: ASCII THUMBNAIL.JPEGInterchangeFormat: 134 THUMBNAIL.JPEGInterchangeFormatLength: 523 COMMENT.0: Comment #1. COMMENT.1: Comment #2. COMMENT.2: Comment #3end THUMBNAIL.JPEGInterchangeFormat: 134 THUMBNAIL.Thumbnail.Height: 1 THUMBNAIL.Thumbnail.Height: 1 ``` **Example #2 **exif\_read\_data()** with streams available as of PHP 7.2.0** ``` <?php // Open a the file, this should be in binary mode $fp = fopen('/path/to/image.jpg', 'rb'); if (!$fp) {     echo 'Error: Unable to open image for reading';     exit; } // Attempt to read the exif headers $headers = exif_read_data($fp); if (!$headers) {     echo 'Error: Unable to read exif headers';     exit; } // Print the 'COMPUTED' headers echo 'EXIF Headers:' . PHP_EOL; foreach ($headers['COMPUTED'] as $header => $value) {     printf(' %s => %s%s', $header, $value, PHP_EOL); } ?> ``` The above example will output something similar to: ``` EXIF Headers: Height => 576 Width => 1024 IsColor => 1 ByteOrderMotorola => 0 ApertureFNumber => f/5.6 UserComment => UserCommentEncoding => UNDEFINED Copyright => Denis Thumbnail.FileType => 2 Thumbnail.MimeType => image/jpeg ``` ### Notes > > **Note**: > > > If [mbstring](https://www.php.net/manual/en/ref.mbstring.php) is enabled, exif will attempt to process the unicode and pick a charset as specified by [exif.decode\_unicode\_motorola](https://www.php.net/manual/en/exif.configuration.php#ini.exif.decode-unicode-motorola) and [exif.decode\_unicode\_intel](https://www.php.net/manual/en/exif.configuration.php#ini.exif.decode-unicode-intel). The exif extension will not attempt to figure out the encoding on its own, and it is up to the user to properly specify the encoding for which to use for decoding by setting one of these two ini directives prior to calling **exif\_read\_data()**. > > > > **Note**: > > > If the `file` is used to pass a stream to this function, then the stream must be seekable. Note that the file pointer position is not changed after this function returns. > > ### See Also * [exif\_thumbnail()](function.exif-thumbnail) - Retrieve the embedded thumbnail of an image * [getimagesize()](function.getimagesize) - Get the size of an image * [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) php The PharException class The PharException class ======================= Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) The PharException class provides a phar-specific exception class for try/catch blocks. Class synopsis -------------- class **PharException** extends [Exception](class.exception) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` }
programming_docs
php Imagick::functionImage Imagick::functionImage ====================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) Imagick::functionImage — Applies a function on the image ### Description ``` public Imagick::functionImage(int $function, array $arguments, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Applies an arithmetic, relational, or logical expression to a pseudo image. See also [» ImageMagick v6 Examples - Image Transformations — Function, Multi-Argument Evaluate](http://www.imagemagick.org/Usage/transform/#function) This method is available if Imagick has been compiled against ImageMagick version 6.4.9 or newer. ### Parameters `function` Refer to this list of [function constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.function) `arguments` Array of arguments to pass to this function. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Create a sinusoidal gradient** ``` <?php $imagick = new Imagick(); $imagick->newPseudoImage(200, 200, 'gradient:black-white'); $arguments = array(3, -90); $imagick->functionImage(Imagick::FUNCTION_SINUSOID, $arguments); header("Content-Type: image/png"); $imagick->setImageFormat("png"); echo $imagick->getImageBlob(); ?> ``` The above example will output something similar to: **Example #2 Create a gradient from the polynomial (4x^2 - 4x + 1)** ``` <?php $imagick = new Imagick(); $imagick->newPseudoImage(200, 200, 'gradient:black-white'); $arguments = array(4, -4, 1); $imagick->functionImage(Imagick::FUNCTION_POLYNOMIAL, $arguments); header("Content-Type: image/png"); $imagick->setimageformat("png"); echo $imagick->getImageBlob(); ?> ``` The above example will output something similar to: **Example #3 Create a complex gradient from the polynomial (4x^2 - 4x^2 + 1) modulated by a sinusoidal gradient** ``` <?php $imagick1 = new Imagick(); $imagick1->newPseudoImage(200, 200, 'gradient:black-white'); $arguments = array(9, -90); $imagick1->functionImage(Imagick::FUNCTION_SINUSOID, $arguments); $imagick2 = new Imagick(); $imagick2->newPseudoImage(200, 200, 'gradient:black-white'); $arguments = array(0.5, 0); $imagick2->functionImage(Imagick::FUNCTION_SINUSOID, $arguments); $imagick1->compositeimage($imagick2, Imagick::COMPOSITE_MULTIPLY, 0, 0); header("Content-Type: image/png"); $imagick1->setImageFormat("png"); echo $imagick1->getImageBlob(); ?> ``` The above example will output something similar to: php Imagick::setSizeOffset Imagick::setSizeOffset ====================== (PECL imagick 2, PECL imagick 3) Imagick::setSizeOffset — Sets the size and offset of the Imagick object ### Description ``` public Imagick::setSizeOffset(int $columns, int $rows, int $offset): bool ``` Sets the size and offset of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `columns` The width in pixels. `rows` The height in pixels. `offset` The image offset. ### Return Values Returns **`true`** on success. php Imagick::queryFormats Imagick::queryFormats ===================== (PECL imagick 2, PECL imagick 3) Imagick::queryFormats — Returns formats supported by Imagick ### Description ``` public static Imagick::queryFormats(string $pattern = "*"): array ``` Returns formats supported by Imagick. ### Parameters `pattern` ### Return Values Returns an array containing the formats supported by Imagick. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::queryFormats()**** ``` <?php     function render() {         $output = "";         $input = \Imagick::queryformats();         $columns = 6;         $output .= "<table border='2'>";         for ($i=0; $i < count($input); $i += $columns) {             $output .= "<tr>";             for ($c=0; $c<$columns; $c++) {                 $output .= "<td>";                 if (($i + $c) <  count($input)) {                     $output .= $input[$i + $c];                 }                 $output .= "</td>";             }             $output .= "</tr>";         }         $output .= "</table>";         return $output;     } ?> ``` php Imagick::affineTransformImage Imagick::affineTransformImage ============================= (PECL imagick 2, PECL imagick 3) Imagick::affineTransformImage — Transforms an image ### Description ``` public Imagick::affineTransformImage(ImagickDraw $matrix): bool ``` Transforms an image as dictated by the affine matrix. ### Parameters `matrix` The affine matrix ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::affineTransformImage()**** ``` <?php function affineTransformImage($imagePath) {     $imagick = new \Imagick(realpath($imagePath));     $draw = new \ImagickDraw();     $angle = deg2rad(40);     $affineRotate = array(         "sx" => cos($angle), "sy" => cos($angle),          "rx" => sin($angle), "ry" => -sin($angle),          "tx" => 0, "ty" => 0,     );     $draw->affine($affineRotate);     $imagick->affineTransformImage($draw);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php Pattern Modifiers Pattern Modifiers ================= The current possible PCRE modifiers are listed below. The names in parentheses refer to internal PCRE names for these modifiers. Spaces and newlines are ignored in modifiers, other characters cause error. > *i* (`PCRE_CASELESS`) If this modifier is set, letters in the pattern match both upper and lower case letters. *m* (`PCRE_MULTILINE`) By default, PCRE treats the subject string as consisting of a single "line" of characters (even if it actually contains several newlines). The "start of line" metacharacter (^) matches only at the start of the string, while the "end of line" metacharacter ($) matches only at the end of the string, or before a terminating newline (unless *D* modifier is set). This is the same as Perl. When this modifier is set, the "start of line" and "end of line" constructs match immediately following or immediately before any newline in the subject string, respectively, as well as at the very start and end. This is equivalent to Perl's /m modifier. If there are no "\n" characters in a subject string, or no occurrences of ^ or $ in a pattern, setting this modifier has no effect. *s* (`PCRE_DOTALL`) If this modifier is set, a dot metacharacter in the pattern matches all characters, including newlines. Without it, newlines are excluded. This modifier is equivalent to Perl's /s modifier. A negative class such as [^a] always matches a newline character, independent of the setting of this modifier. *x* (`PCRE_EXTENDED`) If this modifier is set, whitespace data characters in the pattern are totally ignored except when escaped or inside a character class, and characters between an unescaped # outside a character class and the next newline character, inclusive, are also ignored. This is equivalent to Perl's /x modifier, and makes it possible to include commentary inside complicated patterns. Note, however, that this applies only to data characters. Whitespace characters may never appear within special character sequences in a pattern, for example within the sequence (?( which introduces a conditional subpattern. *A* (`PCRE_ANCHORED`) If this modifier is set, the pattern is forced to be "anchored", that is, it is constrained to match only at the start of the string which is being searched (the "subject string"). This effect can also be achieved by appropriate constructs in the pattern itself, which is the only way to do it in Perl. *D* (`PCRE_DOLLAR_ENDONLY`) If this modifier is set, a dollar metacharacter in the pattern matches only at the end of the subject string. Without this modifier, a dollar also matches immediately before the final character if it is a newline (but not before any other newlines). This modifier is ignored if *m* modifier is set. There is no equivalent to this modifier in Perl. *S* > When a pattern is going to be used several times, it is worth spending more time analyzing it in order to speed up the time taken for matching. If this modifier is set, then this extra analysis is performed. At present, studying a pattern is useful only for non-anchored patterns that do not have a single fixed starting character. *U* (`PCRE_UNGREEDY`) This modifier inverts the "greediness" of the quantifiers so that they are not greedy by default, but become greedy if followed by `?`. It is not compatible with Perl. It can also be set by a (`?U`) [modifier setting within the pattern](regexp.reference.internal-options) or by a question mark behind a quantifier (e.g. `.*?`). > > > > **Note**: > > > > > > It is usually not possible to match more than [pcre.backtrack\_limit](https://www.php.net/manual/en/pcre.configuration.php#ini.pcre.backtrack-limit) characters in ungreedy mode. > > > > > > *X* (`PCRE_EXTRA`) This modifier turns on additional functionality of PCRE that is incompatible with Perl. Any backslash in a pattern that is followed by a letter that has no special meaning causes an error, thus reserving these combinations for future expansion. By default, as in Perl, a backslash followed by a letter with no special meaning is treated as a literal. There are at present no other features controlled by this modifier. *J* (`PCRE_INFO_JCHANGED`) The (?J) internal option setting changes the local `PCRE_DUPNAMES` option. Allow duplicate names for subpatterns. As of PHP 7.2.0 `J` is supported as modifier as well. *u* (`PCRE_UTF8`) This modifier turns on additional functionality of PCRE that is incompatible with Perl. Pattern and subject strings are treated as UTF-8. An invalid subject will cause the preg\_\* function to match nothing; an invalid pattern will trigger an error of level E\_WARNING. Five and six octet UTF-8 sequences are regarded as invalid. php odbc_longreadlen odbc\_longreadlen ================= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_longreadlen — Handling of LONG columns ### Description ``` odbc_longreadlen(resource $statement, int $length): bool ``` Controls handling of `LONG`, `LONGVARCHAR` and `LONGVARBINARY` columns. The default length can be set using the [uodbc.defaultlrl](https://www.php.net/manual/en/odbc.configuration.php#ini.uodbc.defaultlrl) php.ini directive. ### Parameters `statement` The result identifier. `length` The number of bytes returned to PHP is controlled by the parameter length. If it is set to `0`, long column data is passed through to the client (i.e. printed) when retrieved with [odbc\_result()](function.odbc-result). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Notes > > **Note**: > > > Handling of `LONGVARBINARY` columns is also affected by [odbc\_binmode()](function.odbc-binmode). > > php ldap_first_entry ldap\_first\_entry ================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_first\_entry — Return first result id ### Description ``` ldap_first_entry(LDAP\Connection $ldap, LDAP\Result $result): LDAP\ResultEntry|false ``` Returns the entry identifier for first entry in the result. This entry identifier is then supplied to [ldap\_next\_entry()](function.ldap-next-entry) routine to get successive entries from the result. Entries in the LDAP result are read sequentially using the **ldap\_first\_entry()** and [ldap\_next\_entry()](function.ldap-next-entry) functions. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `result` An [LDAP\Result](class.ldap-result) instance, returned by [ldap\_list()](function.ldap-list) or [ldap\_search()](function.ldap-search). ### Return Values Returns an [LDAP\ResultEntry](class.ldap-result-entry) instance, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `result` parameter expects an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | Returns an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was returned. | ### See Also * [ldap\_get\_entries()](function.ldap-get-entries) - Get all result entries php Yaf_Dispatcher::setDefaultController Yaf\_Dispatcher::setDefaultController ===================================== (Yaf >=1.0.0) Yaf\_Dispatcher::setDefaultController — Change default controller name ### Description ``` public Yaf_Dispatcher::setDefaultController(string $controller): Yaf_Dispatcher ``` ### Parameters `controller` ### Return Values php mailparse_msg_extract_whole_part_file mailparse\_msg\_extract\_whole\_part\_file ========================================== (PECL mailparse >= 0.9.0) mailparse\_msg\_extract\_whole\_part\_file — Extracts a message section including headers without decoding the transfer encoding ### Description ``` mailparse_msg_extract_whole_part_file(resource $mimemail, string $filename, callable $callbackfunc = ?): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `mimemail` A valid `MIME` resource. `filename` `callbackfunc` ### Return Values ### See Also * [mailparse\_msg\_extract\_part()](function.mailparse-msg-extract-part) - Extracts/decodes a message section * [mailparse\_msg\_extract\_part\_file()](function.mailparse-msg-extract-part-file) - Extracts/decodes a message section php GmagickDraw::line GmagickDraw::line ================= (PECL gmagick >= Unknown) GmagickDraw::line — Draws a line ### Description ``` public GmagickDraw::line( float $sx, float $sy, float $ex, float $ey ): GmagickDraw ``` Draws a line on the image using the current stroke color, stroke opacity, and stroke width. ### Parameters `sx` starting x ordinate `sy` starting y ordinate `ex` ending x ordinate `ey` ending y ordinate ### Return Values The [GmagickDraw](class.gmagickdraw) object. php Yaf_Dispatcher::setRequest Yaf\_Dispatcher::setRequest =========================== (Yaf >=1.0.0) Yaf\_Dispatcher::setRequest — The setRequest purpose ### Description ``` public Yaf_Dispatcher::setRequest(Yaf_Request_Abstract $request): Yaf_Dispatcher ``` ### Parameters `plugin` ### Return Values php $_FILES $\_FILES ======== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) $\_FILES — HTTP File Upload variables ### Description An associative array of items uploaded to the current script via the HTTP POST method. The structure of this array is outlined in the [POST method uploads](https://www.php.net/manual/en/features.file-upload.post-method.php) section. ### Notes > > **Note**: > > > This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do **global $variable;** to access it within functions or methods. > > > ### See Also * [move\_uploaded\_file()](function.move-uploaded-file) - Moves an uploaded file to a new location * [Handling File Uploads](https://www.php.net/manual/en/features.file-upload.php) php imagepolygon imagepolygon ============ (PHP 4, PHP 5, PHP 7, PHP 8) imagepolygon — Draws a polygon ### Description Signature as of PHP 8.0.0 (not supported with named arguments) ``` imagepolygon(GdImage $image, array $points, int $color): bool ``` Alternative signature (deprecated as of PHP 8.1.0) ``` imagepolygon( GdImage $image, array $points, int $num_points, int $color ): bool ``` **imagepolygon()** creates a polygon in the given `image`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `points` An array containing the polygon's vertices, e.g.: | | | | --- | --- | | points[0] | = x0 | | points[1] | = y0 | | points[2] | = x1 | | points[3] | = y1 | `num_points` Total number of points (vertices), which must be at least 3. If this parameter is omitted as per the second signature, `points` must have an even number of elements, and `num_points` is assumed to be `count($points)/2`. `color` A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The parameter `num_points` has been deprecated. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagepolygon()** example** ``` <?php // Create a blank image $image = imagecreatetruecolor(400, 300); // Allocate a color for the polygon $col_poly = imagecolorallocate($image, 255, 255, 255); // Draw the polygon imagepolygon($image, array(         0,   0,         100, 200,         300, 200     ),     3,     $col_poly); // Output the picture to the browser header('Content-type: image/png'); imagepng($image); imagedestroy($image); ?> ``` The above example will output something similar to: ### See Also * [imagefilledpolygon()](function.imagefilledpolygon) - Draw a filled polygon * [imageopenpolygon()](function.imageopenpolygon) - Draws an open polygon * [imagecreate()](function.imagecreate) - Create a new palette based image * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image php The SensitiveParameter class The SensitiveParameter class ============================ Introduction ------------ (PHP 8 >= 8.2.0) This attribute is used to mark a parameter that is sensitive and should have its value redacted if present in a stack trace. Class synopsis -------------- final class **SensitiveParameter** { } Examples -------- ``` <?php function defaultBehavior(     string $secret,     string $normal ) {     throw new Exception('Error!'); } function sensitiveParametersWithAttribute(     #[\SensitiveParameter]     string $secret,     string $normal ) {     throw new Exception('Error!'); } try {     defaultBehavior('password', 'normal'); } catch (Exception $e) {     echo $e, PHP_EOL, PHP_EOL; } try {     sensitiveParametersWithAttribute('password', 'normal'); } catch (Exception $e) {     echo $e, PHP_EOL, PHP_EOL; } ?> ``` Output of the above example in PHP 8.2 is similar to: ``` Exception: Error! in example.php:7 Stack trace: #0 example.php(19): defaultBehavior('password', 'normal') #1 {main} Exception: Error! in example.php:15 Stack trace: #0 example.php(25): sensitiveParametersWithAttribute(Object(SensitiveParameterValue), 'normal') #1 {main} ``` See Also -------- [Attributes overview](https://www.php.net/manual/en/language.attributes.php) php date_timezone_set date\_timezone\_set =================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) date\_timezone\_set — Alias of [DateTime::setTimezone()](datetime.settimezone) ### Description This function is an alias of: [DateTime::setTimezone()](datetime.settimezone) php GearmanClient::clearCallbacks GearmanClient::clearCallbacks ============================= (PECL gearman >= 0.5.0) GearmanClient::clearCallbacks — Clear all task callback functions ### Description ``` public GearmanClient::clearCallbacks(): bool ``` Clears all the task callback functions that have previously been set. ### Parameters This function has no parameters. ### Return Values Always returns **`true`**. ### See Also * [GearmanClient::setDataCallback()](gearmanclient.setdatacallback) - Callback function when there is a data packet for a task * [GearmanClient::setCompleteCallback()](gearmanclient.setcompletecallback) - Set a function to be called on task completion * [GearmanClient::setCreatedCallback()](gearmanclient.setcreatedcallback) - Set a callback for when a task is queued * [GearmanClient::setExceptionCallback()](gearmanclient.setexceptioncallback) - Set a callback for worker exceptions * [GearmanClient::setFailCallback()](gearmanclient.setfailcallback) - Set callback for job failure * [GearmanClient::setStatusCallback()](gearmanclient.setstatuscallback) - Set a callback for collecting task status * [GearmanClient::setWarningCallback()](gearmanclient.setwarningcallback) - Set a callback for worker warnings * [GearmanClient::setWorkloadCallback()](gearmanclient.setworkloadcallback) - Set a callback for accepting incremental data updates
programming_docs
php EventBase::getMethod EventBase::getMethod ==================== (PECL event >= 1.2.6-beta) EventBase::getMethod — Returns event method in use ### Description ``` public EventBase::getMethod(): string ``` ### Parameters This function has no parameters. ### Return Values String representing used event method(backend). ### Examples **Example #1 **EventBase::getMethod()** example** ``` <?php $cfg = new EventConfig(); if ($cfg->avoidMethod("select")) {     echo "'select' method avoided\n"; } // Create event_base associated with the config $base = new EventBase($cfg); echo "Event method used: ", $base->getMethod(), PHP_EOL; ?> ``` The above example will output something similar to: ``` `select' method avoided Event method used: epoll ``` ### See Also * [EventBase::getFeatures()](eventbase.getfeatures) - Returns bitmask of features supported php XMLReader::moveToAttributeNo XMLReader::moveToAttributeNo ============================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) XMLReader::moveToAttributeNo — Move cursor to an attribute by index ### Description ``` public XMLReader::moveToAttributeNo(int $index): bool ``` Positions cursor on attribute based on its position. ### Parameters `index` The position of the attribute. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [XMLReader::moveToElement()](xmlreader.movetoelement) - Position cursor on the parent Element of current Attribute * [XMLReader::moveToAttribute()](xmlreader.movetoattribute) - Move cursor to a named attribute * [XMLReader::moveToAttributeNs()](xmlreader.movetoattributens) - Move cursor to a named attribute * [XMLReader::moveToFirstAttribute()](xmlreader.movetofirstattribute) - Position cursor on the first Attribute php Ev::verify Ev::verify ========== (PECL ev >= 0.2.0) Ev::verify — Performs internal consistency checks(for debugging) ### Description ``` final public static Ev::verify(): void ``` Performs internal consistency checks(for debugging *libev* ) and abort the program if any data structures were found to be corrupted. ### Parameters This function has no parameters. ### Return Values No value is returned. php mb_strrichr mb\_strrichr ============ (PHP 5 >= 5.2.0, PHP 7, PHP 8) mb\_strrichr — Finds the last occurrence of a character in a string within another, case insensitive ### Description ``` mb_strrichr( string $haystack, string $needle, bool $before_needle = false, ?string $encoding = null ): string|false ``` **mb\_strrichr()** finds the last occurrence of `needle` in `haystack` and returns the portion of `haystack`. Unlike [mb\_strrchr()](function.mb-strrchr), **mb\_strrichr()** is case-insensitive. If `needle` is not found, it returns **`false`**. ### Parameters `haystack` The string from which to get the last occurrence of `needle` `needle` The string to find in `haystack` `before_needle` Determines which portion of `haystack` this function returns. If set to **`true`**, it returns all of `haystack` from the beginning to the last occurrence of `needle`. If set to **`false`**, it returns all of `haystack` from the last occurrence of `needle` to the end, `encoding` Character encoding name to use. If it is omitted, internal character encoding is used. ### Return Values Returns the portion of `haystack`. or **`false`** if `needle` is not found. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `needle` now accepts an empty string. | | 8.0.0 | `encoding` is nullable now. | ### See Also * [mb\_stristr()](function.mb-stristr) - Finds first occurrence of a string within another, case insensitive * [mb\_strrchr()](function.mb-strrchr) - Finds the last occurrence of a character in a string within another php msg_get_queue msg\_get\_queue =============== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) msg\_get\_queue — Create or attach to a message queue ### Description ``` msg_get_queue(int $key, int $permissions = 0666): SysvMessageQueue|false ``` **msg\_get\_queue()** returns an id that can be used to access the System V message queue with the given `key`. The first call creates the message queue with the optional `permissions`. A second call to **msg\_get\_queue()** for the same `key` will return a different message queue identifier, but both identifiers access the same underlying message queue. ### Parameters `key` Message queue numeric ID `permissions` Queue permissions. Default to 0666. If the message queue already exists, the `permissions` will be ignored. ### Return Values Returns [SysvMessageQueue](class.sysvmessagequeue) instance that can be used to access the System V message queue, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [SysvMessageQueue](class.sysvmessagequeue) instance now; previously, a resource was returned. | ### See Also * [msg\_remove\_queue()](function.msg-remove-queue) - Destroy a message queue * [msg\_receive()](function.msg-receive) - Receive a message from a message queue * [msg\_send()](function.msg-send) - Send a message to a message queue * [msg\_stat\_queue()](function.msg-stat-queue) - Returns information from the message queue data structure * [msg\_set\_queue()](function.msg-set-queue) - Set information in the message queue data structure php xml_set_external_entity_ref_handler xml\_set\_external\_entity\_ref\_handler ======================================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_set\_external\_entity\_ref\_handler — Set up external entity reference handler ### Description ``` xml_set_external_entity_ref_handler(XMLParser $parser, callable $handler): bool ``` Sets the external entity reference handler function for the XML parser `parser`. ### Parameters `parser` A reference to the XML parser to set up external entity reference handler function. `handler` `handler` is a string containing the name of a function that must exist when [xml\_parse()](function.xml-parse) is called for `parser`. The function named by `handler` must accept five parameters, and should return an integer value.If the value returned from the handler is **`false`** (which it will be if no value is returned), the XML parser will stop parsing and [xml\_get\_error\_code()](function.xml-get-error-code) will return **`XML_ERROR_EXTERNAL_ENTITY_HANDLING`**. ``` handler( XMLParser $parser, string $open_entity_names, string $base, string $system_id, string $public_id ) ``` `parser` The first parameter, parser, is a reference to the XML parser calling the handler. `open_entity_names` The second parameter, `open_entity_names`, is a space-separated list of the names of the entities that are open for the parse of this entity (including the name of the referenced entity). `base` This is the base for resolving the system identifier (`system_id`) of the external entity.Currently this parameter will always be set to an empty string. `system_id` The fourth parameter, `system_id`, is the system identifier as specified in the entity declaration. `public_id` The fifth parameter, `public_id`, is the public identifier as specified in the entity declaration, or an empty string if none was specified; the whitespace in the public identifier will have been normalized as required by the XML spec. If a handler function is set to an empty string, or **`false`**, the handler in question is disabled. > **Note**: Instead of a function name, an array containing an object reference and a method name can also be supplied. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `parser` expects an [XMLParser](class.xmlparser) instance now; previously, a resource was expected. | | 7.3.0 | The return value of the `handler` is no longer ignored if the extension has been built against libxml. Formerly, the return value has been ignored, and parsing did never stop. | php SolrParams::set SolrParams::set =============== (PECL solr >= 0.9.2) SolrParams::set — Alias of [SolrParams::setParam()](solrparams.setparam) ### Description ``` final public SolrParams::set(string $name, string $value): void ``` An alias of SolrParams::setParam ### Parameters `name` Then name of the parameter `value` The parameter value ### Return Values Returns an instance of the SolrParams object on success php ReflectionFunctionAbstract::getClosureUsedVariables ReflectionFunctionAbstract::getClosureUsedVariables =================================================== (PHP 8 >= 8.1.0) ReflectionFunctionAbstract::getClosureUsedVariables — Returns an array of the used variables in the Closure ### Description ``` public ReflectionFunctionAbstract::getClosureUsedVariables(): array ``` Returns an array of the used variables in the [Closure](class.closure). ### Parameters This function has no parameters. ### Return Values Returns an array of the used variables in the [Closure](class.closure). ### Examples **Example #1 **ReflectionFunctionAbstract::getClosureUsedVariables()** example** ``` <?php $one = 1; $two = 2; $function = function() use ($one, $two) {     static $three = 3; }; $reflector = new ReflectionFunction($function); var_dump($reflector->getClosureUsedVariables()); ?> ``` The above example will output something similar to: ``` array(2) { ["one"]=> int(1) ["two"]=> int(2) } ``` ### See Also * [ReflectionFunctionAbstract::getClosureScopeClass()](reflectionfunctionabstract.getclosurescopeclass) - Returns the scope associated to the closure * [ReflectionFunctionAbstract::getClosureThis()](reflectionfunctionabstract.getclosurethis) - Returns this pointer bound to closure php SolrQuery::removeField SolrQuery::removeField ====================== (PECL solr >= 0.9.2) SolrQuery::removeField — Removes a field from the list of fields ### Description ``` public SolrQuery::removeField(string $field): SolrQuery ``` Removes a field from the list of fields ### Parameters `field` Name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php ldap_next_attribute ldap\_next\_attribute ===================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_next\_attribute — Get the next attribute in result ### Description ``` ldap_next_attribute(LDAP\Connection $ldap, LDAP\ResultEntry $entry): string|false ``` Retrieves the attributes in an entry. The first call to **ldap\_next\_attribute()** is made with the `entry` returned from [ldap\_first\_attribute()](function.ldap-first-attribute). ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `entry` An [LDAP\ResultEntry](class.ldap-result-entry) instance. ### Return Values Returns the next attribute in an entry on success and **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `entry` parameter expects an [LDAP\ResultEntry](class.ldap-result-entry) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | The unused third parameter `ber_identifier` is no longer accepted. | ### See Also * [ldap\_get\_attributes()](function.ldap-get-attributes) - Get attributes from a search result entry php mysqli_result::free mysqli\_result::free ==================== mysqli\_result::close ===================== mysqli\_result::free\_result ============================ mysqli\_free\_result ==================== (PHP 5, PHP 7, PHP 8) mysqli\_result::free -- mysqli\_result::close -- mysqli\_result::free\_result -- mysqli\_free\_result — Frees the memory associated with a result ### Description Object-oriented style ``` public mysqli_result::free(): void ``` ``` public mysqli_result::close(): void ``` ``` public mysqli_result::free_result(): void ``` Procedural style ``` mysqli_free_result(mysqli_result $result): void ``` Frees the memory associated with the result. ### Parameters `result` Procedural style only: A [mysqli\_result](class.mysqli-result) object returned by [mysqli\_query()](mysqli.query), [mysqli\_store\_result()](mysqli.store-result), [mysqli\_use\_result()](mysqli.use-result) or [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). ### Return Values No value is returned. ### See Also * [mysqli\_query()](mysqli.query) - Performs a query on the database * [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) - Gets a result set from a prepared statement as a mysqli\_result object * [mysqli\_store\_result()](mysqli.store-result) - Transfers a result set from the last query * [mysqli\_use\_result()](mysqli.use-result) - Initiate a result set retrieval php None Enumerations overview --------------------- (PHP 8 >= 8.1.0) Enumerations, or "Enums" allow a developer to define a custom type that is limited to one of a discrete number of possible values. That can be especially helpful when defining a domain model, as it enables "making invalid states unrepresentable." Enums appear in many languages with a variety of different features. In PHP, Enums are a special kind of object. The Enum itself is a class, and its possible cases are all single-instance objects of that class. That means Enum cases are valid objects and may be used anywhere an object may be used, including type checks. The most popular example of enumerations is the built-in boolean type, which is an enumerated type with legal values **`true`** and **`false`**. Enums allows developers to define their own arbitrarily robust enumerations. php IntlChar::getCombiningClass IntlChar::getCombiningClass =========================== (PHP 7, PHP 8) IntlChar::getCombiningClass — Get the combining class of a code point ### Description ``` public static IntlChar::getCombiningClass(int|string $codepoint): ?int ``` Returns the combining class of the code point. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns the combining class of the character. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::getCombiningClass("A")); var_dump(IntlChar::getCombiningClass("\u{0334}")); var_dump(IntlChar::getCombiningClass("\u{0358}")); ?> ``` The above example will output: ``` int(0) int(1) int(232) ``` php DirectoryIterator::isLink DirectoryIterator::isLink ========================= (PHP 5, PHP 7, PHP 8) DirectoryIterator::isLink — Determine if current DirectoryIterator item is a symbolic link ### Description ``` public DirectoryIterator::isLink(): bool ``` Determines if the current [DirectoryIterator](class.directoryiterator) item is a symbolic link. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the item is a symbolic link, otherwise **`false`** ### Examples **Example #1 A **DirectoryIterator::isLink()** example** This example contains a recursive function for removing a directory tree. ``` <?php /**  * This function will recursively delete all files in the given path, without  * following symlinks.  *   * @param string $path Path to the directory to remove.  */ function removeDir($path) {     $dir = new DirectoryIterator($path);     foreach ($dir as $fileinfo) {         if ($fileinfo->isFile() || $fileinfo->isLink()) {             unlink($fileinfo->getPathName());         } elseif (!$fileinfo->isDot() && $fileinfo->isDir()) {             removeDir($fileinfo->getPathName());         }     }     rmdir($path); } removeDir('foo'); ?> ``` ### See Also * [DirectoryIterator::getType()](directoryiterator.gettype) - Determine the type of the current DirectoryIterator item * [DirectoryIterator::isDir()](directoryiterator.isdir) - Determine if current DirectoryIterator item is a directory * [DirectoryIterator::isDot()](directoryiterator.isdot) - Determine if current DirectoryIterator item is '.' or '..' * [DirectoryIterator::isFile()](directoryiterator.isfile) - Determine if current DirectoryIterator item is a regular file php Imagick::deconstructImages Imagick::deconstructImages ========================== (PECL imagick 2, PECL imagick 3) Imagick::deconstructImages — Returns certain pixel differences between images ### Description ``` public Imagick::deconstructImages(): Imagick ``` Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. ### Parameters This function has no parameters. ### Return Values Returns a new Imagick object on success. ### Errors/Exceptions Throws ImagickException on error. php PhpToken::getTokenName PhpToken::getTokenName ====================== (PHP 8) PhpToken::getTokenName — Returns the name of the token. ### Description ``` public PhpToken::getTokenName(): ?string ``` Returns the name of the token. ### Parameters This function has no parameters. ### Return Values An ASCII character for single-char tokens, or one of T\_\* constant names for known tokens (see [List of Parser Tokens](https://www.php.net/manual/en/tokens.php)), or **`null`** for unknown tokens. ### Examples **Example #1 **PhpToken::getTokenName()** example** ``` <?php // known token $token = new PhpToken(T_ECHO, 'echo'); var_dump($token->getTokenName());   // -> string(6) "T_ECHO" // single-char token $token = new PhpToken(ord(';'), ';'); var_dump($token->getTokenName());   // -> string(1) ";" // unknown token $token = new PhpToken(10000 , "\0"); var_dump($token->getTokenName());   // -> NULL ``` ### See Also * [PhpToken::tokenize()](phptoken.tokenize) - Splits given source into PHP tokens, represented by PhpToken objects. * [token\_name()](function.token-name) - Get the symbolic name of a given PHP token php Gmagick::setimagedelay Gmagick::setimagedelay ====================== (PECL gmagick >= Unknown) Gmagick::setimagedelay — Sets the image delay ### Description ``` public Gmagick::setimagedelay(int $delay): Gmagick ``` Sets the image delay. ### Parameters `delay` The image delay in 1/100th of a second. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php Fiber::getCurrent Fiber::getCurrent ================= (PHP 8 >= 8.1.0) Fiber::getCurrent — Gets the currently executing Fiber instance ### Description ``` public static Fiber::getCurrent(): ?Fiber ``` ### Parameters This function has no parameters. ### Return Values Returns the currently executing [Fiber](class.fiber) instance or **`null`** if this method is called from outside a fiber. php Imagick::mapImage Imagick::mapImage ================= (PECL imagick 2, PECL imagick 3) Imagick::mapImage — Replaces the colors of an image with the closest color from a reference image **Warning**This function has been *DEPRECATED* as of Imagick 3.4.4. Relying on this function is highly discouraged. ### Description ``` public Imagick::mapImage(Imagick $map, bool $dither): bool ``` ### Parameters `map` `dither` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error.
programming_docs
php SessionHandlerInterface::open SessionHandlerInterface::open ============================= (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandlerInterface::open — Initialize session ### Description ``` public SessionHandlerInterface::open(string $path, string $name): bool ``` Re-initialize existing session, or creates a new one. Called when a session starts or when [session\_start()](function.session-start) is invoked. ### Parameters `path` The path where to store/retrieve the session. `name` The session name. ### Return Values The return value (usually **`true`** on success, **`false`** on failure). Note this value is returned internally to PHP for processing. ### See Also * [session\_name()](function.session-name) - Get and/or set the current session name * The [session.auto-start](https://www.php.net/manual/en/session.configuration.php#ini.session.auto-start) configuration directive. php geoip_db_avail geoip\_db\_avail ================ (PECL geoip >= 1.0.1) geoip\_db\_avail — Determine if GeoIP Database is available ### Description ``` geoip_db_avail(int $database): bool ``` The **geoip\_db\_avail()** function returns if the corresponding GeoIP Database is available and can be opened on disk. It does not indicate if the file is a proper database, only if it is readable. ### Parameters `database` The database type as an integer. You can use the [various constants](https://www.php.net/manual/en/geoip.constants.php) defined with this extension (ie: GEOIP\_\*\_EDITION). ### Return Values Returns **`true`** is database exists, **`false`** if not found, or **`null`** on error. ### Examples **Example #1 A **geoip\_db\_avail()** example** This will output the current database version string. ``` <?php if (geoip_db_avail(GEOIP_COUNTRY_EDITION))     print geoip_database_info(GEOIP_COUNTRY_EDITION); ?> ``` The above example will output: ``` GEO-106FREE 20080801 Build 1 Copyright (c) 2006 MaxMind LLC All Rights Reserved ``` php ReflectionEnumBackedCase::__construct ReflectionEnumBackedCase::\_\_construct ======================================= (PHP 8 >= 8.1.0) ReflectionEnumBackedCase::\_\_construct — Instantiates a [ReflectionEnumBackedCase](class.reflectionenumbackedcase) object ### Description public **ReflectionEnumBackedCase::\_\_construct**(object|string `$class`, string `$constant`) ### Parameters `class` An enum instance or a name. `constant` An enum constant name. php define define ====== (PHP 4, PHP 5, PHP 7, PHP 8) define — Defines a named constant ### Description ``` define(string $constant_name, mixed $value, bool $case_insensitive = false): bool ``` Defines a named constant at runtime. ### Parameters `constant_name` The name of the constant. > > **Note**: > > > It is possible to **define()** constants with reserved or even invalid names, whose value can (only) be retrieved with [constant()](function.constant). However, doing so is not recommended. > > `value` The value of the constant. In PHP 5, `value` must be a scalar value (int, float, string, bool, or **`null`**). In PHP 7, array values are also accepted. **Warning** While it is possible to define resource constants, it is not recommended and may cause unpredictable behavior. `case_insensitive` If set to **`true`**, the constant will be defined case-insensitive. The default behavior is case-sensitive; i.e. `CONSTANT` and `Constant` represent different values. **Warning** Defining case-insensitive constants is deprecated as of PHP 7.3.0. As of PHP 8.0.0, only `false` is an acceptable value, passing `true` will produce a warning. > > **Note**: > > > Case-insensitive constants are stored as lower-case. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Passing **`true`** to `case_insensitive` now emits an **`E_WARNING`**. Passing **`false`** is still allowed. | | 7.3.0 | `case_insensitive` has been deprecated and will be removed in version 8.0.0. | | 7.0.0 | array values are allowed. | ### Examples **Example #1 Defining Constants** ``` <?php define("CONSTANT", "Hello world."); echo CONSTANT; // outputs "Hello world." echo Constant; // outputs "Constant" and issues a notice. define("GREETING", "Hello you.", true); echo GREETING; // outputs "Hello you." echo Greeting; // outputs "Hello you." // Works as of PHP 7 define('ANIMALS', array(     'dog',     'cat',     'bird' )); echo ANIMALS[1]; // outputs "cat" ?> ``` **Example #2 Constants with Reserved Names** This example illustrates the *possibility* to define a constant with the same name as a [magic constant](language.constants.predefined). Since the resulting behavior is obviously confusing, it is not recommended to do this in practise, though. ``` <?php var_dump(defined('__LINE__')); var_dump(define('__LINE__', 'test')); var_dump(constant('__LINE__')); var_dump(__LINE__); ?> ``` The above example will output: ``` bool(false) bool(true) string(4) "test" int(5) ``` ### See Also * [defined()](function.defined) - Checks whether a given named constant exists * [constant()](function.constant) - Returns the value of a constant * The section on [Constants](language.constants) php ArrayObject::natcasesort ArrayObject::natcasesort ======================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ArrayObject::natcasesort — Sort an array using a case insensitive "natural order" algorithm ### Description ``` public ArrayObject::natcasesort(): bool ``` This method is a case insensitive version of [ArrayObject::natsort](arrayobject.natsort). This method implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". > > **Note**: > > > If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. > > ### Parameters This function has no parameters. ### Return Values No value is returned. ### Examples **Example #1 **ArrayObject::natcasesort()** example** ``` <?php $array = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png'); $arr1 = new ArrayObject($array); $arr2 = clone $arr1; $arr1->asort(); echo "Standard sorting\n"; print_r($arr1); $arr2->natcasesort(); echo "\nNatural order sorting (case-insensitive)\n"; print_r($arr2); ?> ``` The above example will output: ``` Standard sorting ArrayObject Object ( [0] => IMG0.png [5] => IMG3.png [4] => img1.png [2] => img10.png [1] => img12.png [3] => img2.png ) Natural order sorting (case-insensitive) ArrayObject Object ( [0] => IMG0.png [4] => img1.png [3] => img2.png [5] => IMG3.png [2] => img10.png [1] => img12.png ) ``` For more information see: Martin Pool's [» Natural Order String Comparison](https://github.com/sourcefrog/natsort) page. ### See Also * [ArrayObject::asort()](arrayobject.asort) - Sort the entries by value * [ArrayObject::ksort()](arrayobject.ksort) - Sort the entries by key * [ArrayObject::natsort()](arrayobject.natsort) - Sort entries using a "natural order" algorithm * [ArrayObject::uasort()](arrayobject.uasort) - Sort the entries with a user-defined comparison function and maintain key association * [ArrayObject::uksort()](arrayobject.uksort) - Sort the entries by keys using a user-defined comparison function * [natcasesort()](function.natcasesort) - Sort an array using a case insensitive "natural order" algorithm php Gmagick::thumbnailimage Gmagick::thumbnailimage ======================= (PECL gmagick >= Unknown) Gmagick::thumbnailimage — Changes the size of an image ### Description ``` public Gmagick::thumbnailimage(int $width, int $height, bool $fit = false): Gmagick ``` Changes the size of an image to the given dimensions and removes any associated profiles. The goal is to produce small low cost thumbnail images suited for display on the Web. If **`true`** is given as a third parameter then columns and rows parameters are used as maximums for each side. Both sides will be scaled down until the match or are smaller than the parameter given for the side. ### Parameters `width` Image width. `height` Image height. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php jdtogregorian jdtogregorian ============= (PHP 4, PHP 5, PHP 7, PHP 8) jdtogregorian — Converts Julian Day Count to Gregorian date ### Description ``` jdtogregorian(int $julian_day): string ``` Converts Julian Day Count to a string containing the Gregorian date in the format of "month/day/year". ### Parameters `julian_day` A julian day number as integer ### Return Values The gregorian date as a string in the form "month/day/year" ### See Also * [gregoriantojd()](function.gregoriantojd) - Converts a Gregorian date to Julian Day Count * [cal\_from\_jd()](function.cal-from-jd) - Converts from Julian Day Count to a supported calendar php GearmanClient::addOptions GearmanClient::addOptions ========================= (PECL gearman >= 0.6.0) GearmanClient::addOptions — Add client options ### Description ``` public GearmanClient::addOptions(int $options): bool ``` Adds one or more options to those already set. ### Parameters `options` The options to add. One of the following constants, or a combination of them using the bitwise OR operator (|): **`GEARMAN_CLIENT_GENERATE_UNIQUE`**, **`GEARMAN_CLIENT_NON_BLOCKING`**, **`GEARMAN_CLIENT_UNBUFFERED_RESULT`** or **`GEARMAN_CLIENT_FREE_TASKS`**. ### Return Values Always returns **`true`**. php Imagick::optimizeImageLayers Imagick::optimizeImageLayers ============================ (PECL imagick 2, PECL imagick 3) Imagick::optimizeImageLayers — Removes repeated portions of images to optimize ### Description ``` public Imagick::optimizeImageLayers(): bool ``` Compares each image the GIF disposed forms of the previous image in the sequence. From this it attempts to select the smallest cropped image to replace each frame, while preserving the results of the animation. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::optimizeImageLayers()**** Reading, optimizing and writing a GIF image ``` <?php /* create new imagick object */ $im = new Imagick("test.gif"); /* optimize the image layers */ $im->optimizeImageLayers(); /* write the image back */ $im->writeImages("test_optimized.gif", true); ?> ``` ### See Also * [Imagick::compareImageLayers()](imagick.compareimagelayers) - Returns the maximum bounding region between images * [Imagick::writeImages()](imagick.writeimages) - Writes an image or image sequence * [Imagick::writeImage()](imagick.writeimage) - Writes an image to the specified filename php Yaf_Dispatcher::getRouter Yaf\_Dispatcher::getRouter ========================== (Yaf >=1.0.0) Yaf\_Dispatcher::getRouter — Retrive router instance ### Description ``` public Yaf_Dispatcher::getRouter(): Yaf_Router ``` ### Parameters This function has no parameters. ### Return Values php php_user_filter::onCreate php\_user\_filter::onCreate =========================== (PHP 5, PHP 7, PHP 8) php\_user\_filter::onCreate — Called when creating the filter ### Description ``` public php_user_filter::onCreate(): bool ``` This method is called during instantiation of the filter class object. If your filter allocates or initializes any other resources (such as a buffer), this is the place to do it. When your filter is first instantiated, and `yourfilter->onCreate()` is called, a number of properties will be available as shown in the table below. | Property | Contents | | --- | --- | | `FilterClass->filtername` | A string containing the name the filter was instantiated with. Filters may be registered under multiple names or under wildcards. Use this property to determine which name was used. | | `FilterClass->params` | The contents of the `params` parameter passed to [stream\_filter\_append()](function.stream-filter-append) or [stream\_filter\_prepend()](function.stream-filter-prepend). | | `FilterClass->stream` | The stream resource being filtered. Maybe available only during **filter()** calls when the `closing` parameter is set to **`false`**. | ### Parameters This function has no parameters. ### Return Values Your implementation of this method should return **`false`** on failure, or **`true`** on success. php sodium_crypto_generichash sodium\_crypto\_generichash =========================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_generichash — Get a hash of the message ### Description ``` sodium_crypto_generichash(string $message, string $key = "", int $length = SODIUM_CRYPTO_GENERICHASH_BYTES): string ``` Hash a message with BLAKE2b. ### Parameters `message` The message being hashed. `key` (Optional) cryptographic key. This serves the same function as a HMAC key, but it's utilized as a reserved section of the internal BLAKE2 state. `length` Output size. ### Return Values The cryptographic hash as raw bytes. If a hex-encoded output is desired, the result can be passed to [sodium\_bin2hex()](function.sodium-bin2hex). php xmlrpc_decode_request xmlrpc\_decode\_request ======================= (PHP 4 >= 4.1.0, PHP 5, PHP 7) xmlrpc\_decode\_request — Decodes XML into native PHP types ### Description ``` xmlrpc_decode_request(string $xml, string &$method, string $encoding = ?): mixed ``` **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. **Warning**This function is currently not documented; only its argument list is available. php None Variables From External Sources ------------------------------- ### HTML Forms (GET and POST) When a form is submitted to a PHP script, the information from that form is automatically made available to the script. There are few ways to access this information, for example: **Example #1 A simple HTML form** ``` <form action="foo.php" method="post"> Name: <input type="text" name="username" /><br /> Email: <input type="text" name="email" /><br /> <input type="submit" name="submit" value="Submit me!" /> </form> ``` There are only two ways to access data from your HTML forms. Currently available methods are listed below: **Example #2 Accessing data from a simple POST HTML form** ``` <?php echo $_POST['username']; echo $_REQUEST['username']; ?> ``` Using a GET form is similar except you'll use the appropriate GET predefined variable instead. GET also applies to the `QUERY_STRING` (the information after the '?' in a URL). So, for example, `http://www.example.com/test.php?id=3` contains GET data which is accessible with [$\_GET['id']](reserved.variables.get). See also [$\_REQUEST](reserved.variables.request). > > **Note**: > > > Dots and spaces in variable names are converted to underscores. For example `<input name="a.b" />` becomes `$_REQUEST["a_b"]`. > > PHP also understands arrays in the context of form variables (see the [related faq](https://www.php.net/manual/en/faq.php.html)). You may, for example, group related variables together, or use this feature to retrieve values from a multiple select input. For example, let's post a form to itself and upon submission display the data: **Example #3 More complex form variables** ``` <?php if ($_POST) {     echo '<pre>';     echo htmlspecialchars(print_r($_POST, true));     echo '</pre>'; } ?> <form action="" method="post">     Name:  <input type="text" name="personal[name]" /><br />     Email: <input type="text" name="personal[email]" /><br />     Beer: <br />     <select multiple name="beer[]">         <option value="warthog">Warthog</option>         <option value="guinness">Guinness</option>         <option value="stuttgarter">Stuttgarter Schwabenbräu</option>     </select><br />     <input type="submit" value="submit me!" /> </form> ``` > **Note**: If an external variable name begins with a valid array syntax, trailing characters are silently ignored. For example, `<input name="foo[bar]baz">` becomes `$_REQUEST['foo']['bar']`. > > #### IMAGE SUBMIT variable names When submitting a form, it is possible to use an image instead of the standard submit button with a tag like: ``` <input type="image" src="image.gif" name="sub" /> ``` When the user clicks somewhere on the image, the accompanying form will be transmitted to the server with two additional variables, sub\_x and sub\_y. These contain the coordinates of the user click within the image. The experienced may note that the actual variable names sent by the browser contains a period rather than an underscore, but PHP converts the period to an underscore automatically. ### HTTP Cookies PHP transparently supports HTTP cookies as defined by [» RFC 6265](http://www.faqs.org/rfcs/rfc6265). Cookies are a mechanism for storing data in the remote browser and thus tracking or identifying return users. You can set cookies using the [setcookie()](function.setcookie) function. Cookies are part of the HTTP header, so the SetCookie function must be called before any output is sent to the browser. This is the same restriction as for the [header()](function.header) function. Cookie data is then available in the appropriate cookie data arrays, such as [$\_COOKIE](reserved.variables.cookies) as well as in [$\_REQUEST](reserved.variables.request). See the [setcookie()](function.setcookie) manual page for more details and examples. > **Note**: As of PHP 7.2.34, 7.3.23 and 7.4.11, respectively, the *names* of incoming cookies are no longer url-decoded for security reasons. > > If you wish to assign multiple values to a single cookie variable, you may assign it as an array. For example: ``` <?php   setcookie("MyCookie[foo]", 'Testing 1', time()+3600);   setcookie("MyCookie[bar]", 'Testing 2', time()+3600); ?> ``` That will create two separate cookies although MyCookie will now be a single array in your script. If you want to set just one cookie with multiple values, consider using [serialize()](function.serialize) or [explode()](function.explode) on the value first. Note that a cookie will replace a previous cookie by the same name in your browser unless the path or domain is different. So, for a shopping cart application you may want to keep a counter and pass this along. i.e. **Example #4 A [setcookie()](function.setcookie) example** ``` <?php if (isset($_COOKIE['count'])) {     $count = $_COOKIE['count'] + 1; } else {     $count = 1; } setcookie('count', $count, time()+3600); setcookie("Cart[$count]", $item, time()+3600); ?> ``` ### Dots in incoming variable names Typically, PHP does not alter the names of variables when they are passed into a script. However, it should be noted that the dot (period, full stop) is not a valid character in a PHP variable name. For the reason, look at it: ``` <?php $varname.ext;  /* invalid variable name */ ?> ``` Now, what the parser sees is a variable named $varname, followed by the string concatenation operator, followed by the barestring (i.e. unquoted string which doesn't match any known key or reserved words) 'ext'. Obviously, this doesn't have the intended result. For this reason, it is important to note that PHP will automatically replace any dots in incoming variable names with underscores. ### Determining variable types Because PHP determines the types of variables and converts them (generally) as needed, it is not always obvious what type a given variable is at any one time. PHP includes several functions which find out what type a variable is, such as: [gettype()](function.gettype), [is\_array()](function.is-array), [is\_float()](function.is-float), [is\_int()](function.is-int), [is\_object()](function.is-object), and [is\_string()](function.is-string). See also the chapter on [Types](https://www.php.net/manual/en/language.types.php). HTTP being a text protocol, most, if not all, content that comes in [Superglobal arrays](language.variables.superglobals), like [$\_POST](reserved.variables.post) and [$\_GET](reserved.variables.get) will remain as strings. PHP will not try to convert values to a specific type. In the example below, [$\_GET["var1"]](reserved.variables.get) will contain the string "null" and [$\_GET["var2"]](reserved.variables.get), the string "123". ``` /index.php?var1=null&var2=123 ``` ### Changelog | Version | Description | | --- | --- | | 7.2.34, 7.3.23, 7.4.11 | The *names* of incoming cookies are no longer url-decoded for security reasons. |
programming_docs
php Ds\Hashable::equals Ds\Hashable::equals =================== (PECL ds >= 1.0.0) Ds\Hashable::equals — Determines whether an object is equal to the current instance ### Description ``` abstract public Ds\Hashable::equals(object $obj): bool ``` Determines whether another object is equal to the current instance. This method allows objects to be used as keys in structures such as **Ds\Map** and **Ds\Set**, or any other lookup structure that honors this interface. > > **Note**: > > > It's guaranteed that `obj` is an instance of the same class. > > **Caution** It's important that objects which are equal also have the same hash value. See [Ds\Hashable::hash()](ds-hashable.hash). ### Parameters `obj` The object to compare the current instance to, which is always an instance of the same class. ### Return Values **`true`** if equal, **`false`** otherwise. php IntlChar::getPropertyValueEnum IntlChar::getPropertyValueEnum ============================== (PHP 7, PHP 8) IntlChar::getPropertyValueEnum — Get the property value for a given value name ### Description ``` public static IntlChar::getPropertyValueEnum(int $property, string $name): int ``` Returns the property value integer for a given value name, as specified in the Unicode database file PropertyValueAliases.txt. Short, long, and any other variants are recognized. > > **Note**: > > > Some of the names in PropertyValueAliases.txt will only be recognized with **`IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`**, not **`IntlChar::PROPERTY_GENERAL_CATEGORY`**. These include: > > > * "C" / "Other" > * "L" / "Letter" > * "LC" / "Cased\_Letter" > * "M" / "Mark" > * "N" / "Number" > * "P" / "Punctuation" > * "S" / "Symbol" > * "Z" / "Separator" > > ### Parameters `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). If out of range, or this method doesn't work with the given value, **`IntlChar::PROPERTY_INVALID_CODE`** is returned. `name` The value name to be matched. The name is compared using "loose matching" as described in PropertyValueAliases.txt. ### Return Values Returns the corresponding value integer, or **`IntlChar::PROPERTY_INVALID_CODE`** if the given name does not match any value of the given property, or if the property is invalid. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BLOCK, 'greek') === IntlChar::BLOCK_CODE_GREEK); var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'RIGHT_TO_LEFT') === IntlChar::CHAR_DIRECTION_RIGHT_TO_LEFT); var_dump(IntlChar::getPropertyValueEnum(IntlChar::PROPERTY_BIDI_CLASS, 'some made-up string') === IntlChar::PROPERTY_INVALID_CODE); var_dump(IntlChar::getPropertyValueEnum(123456789, 'RIGHT_TO_LEFT') === IntlChar::PROPERTY_INVALID_CODE); ?> ``` The above example will output: ``` bool(true) bool(true) bool(true) bool(true) ``` php Gmagick::deconstructimages Gmagick::deconstructimages ========================== (PECL gmagick >= Unknown) Gmagick::deconstructimages — Returns certain pixel differences between images ### Description ``` public Gmagick::deconstructimages(): Gmagick ``` Compares each image with the next in a sequence and returns the maximum bounding region of any pixel differences it discovers. ### Parameters This function has no parameters. ### Return Values Returns a new [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php SessionHandler::write SessionHandler::write ===================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandler::write — Write session data ### Description ``` public SessionHandler::write(string $id, string $data): bool ``` Writes the session data to the session storage. Called by normal PHP shutdown, by [session\_write\_close()](function.session-write-close), or when [session\_register\_shutdown()](function.session-register-shutdown) fails. PHP will call [SessionHandler::close()](sessionhandler.close) immediately after this method returns. This method wraps the internal PHP save handler defined in the [session.save\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.save-handler) ini setting that was set before this handler was set by [session\_set\_save\_handler()](function.session-set-save-handler). If this class is extended by inheritance, calling the parent `write` method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows this method to be overridden and or intercepted and filtered (for example, encrypting the `$data` value before sending it to the parent `write` method). For more information on what this method is expected to do, please refer to the documentation at [SessionHandlerInterface::write()](sessionhandlerinterface.write). ### Parameters `id` The session id. `data` The encoded session data. This data is the result of the PHP internally encoding the [$\_SESSION](reserved.variables.session) superglobal to a serialized string and passing it as this parameter. Please note sessions use an alternative serialization method. ### Return Values The return value (usually **`true`** on success, **`false`** on failure). Note this value is returned internally to PHP for processing. ### See Also * The [session.serialize\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.serialize-handler) configuration directive. php The Yaf_Exception_LoadFailed_Controller class The Yaf\_Exception\_LoadFailed\_Controller class ================================================ Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Exception\_LoadFailed\_Controller** extends [Yaf\_Exception\_LoadFailed](class.yaf-exception-loadfailed) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/ ``` public Yaf_Exception::getPrevious(): void ``` } php stomp_connect_error stomp\_connect\_error ===================== (PECL stomp >= 0.3.0) stomp\_connect\_error — Returns a string description of the last connect error ### Description ``` stomp_connect_error(): string ``` Returns a string description of the last connect error. ### Parameters This function has no parameters. ### Return Values A string that describes the error, or **`null`** if no error occurred. ### Examples **Example #1 **stomp\_connect\_error()** example** ``` <?php $link = stomp_connect('http://localhost:61613'); if(!$link) {     die('Connection failed: ' . stomp_connect_error()); } ?> ``` The above example will output something similar to: ``` Connection failed: Invalid Broker URI scheme ``` php ImagickDraw::setStrokeMiterLimit ImagickDraw::setStrokeMiterLimit ================================ (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeMiterLimit — Specifies the miter limit ### Description ``` public ImagickDraw::setStrokeMiterLimit(int $miterlimit): bool ``` **Warning**This function is currently not documented; only its argument list is available. Specifies the miter limit. When two line segments meet at a sharp angle and miter joins have been specified for 'lineJoin', it is possible for the miter to extend far beyond the thickness of the line stroking the path. The miterLimit' imposes a limit on the ratio of the miter length to the 'lineWidth'. ### Parameters `miterlimit` the miter limit ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeMiterLimit()** example** ``` <?php function setStrokeMiterLimit($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setStrokeOpacity(0.6);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(10);     $yOffset = 100;     $draw->setStrokeLineJoin(\Imagick::LINEJOIN_MITER);     for ($y = 0; $y < 3; $y++) {         $draw->setStrokeMiterLimit(40 * $y);         $points = [             ['x' => 22 * 3, 'y' => 15 * 4 + $y * $yOffset],             ['x' => 20 * 3, 'y' => 20 * 4 + $y * $yOffset],             ['x' => 70 * 5, 'y' => 45 * 4 + $y * $yOffset],         ];         $draw->polygon($points);     }     $image = new \Imagick();     $image->newImage(500, 500, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     $image->setImageType(\Imagick::IMGTYPE_PALETTE);     $image->setImageCompressionQuality(100);     $image->stripImage();     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php Ds\Map::first Ds\Map::first ============= (PECL ds >= 1.0.0) Ds\Map::first — Returns the first pair in the map ### Description ``` public Ds\Map::first(): Ds\Pair ``` Returns the first pair in the map. ### Parameters This function has no parameters. ### Return Values The first pair in the map. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Map::first()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->first()); ?> ``` The above example will output something similar to: ``` object(Ds\Pair)#2 (2) { ["key"]=> string(1) "a" ["value"]=> int(1) } ``` php stream_bucket_new stream\_bucket\_new =================== (PHP 5, PHP 7, PHP 8) stream\_bucket\_new — Create a new bucket for use on the current stream ### Description ``` stream_bucket_new(resource $stream, string $buffer): object ``` **Warning**This function is currently not documented; only its argument list is available. php ArrayAccess::offsetSet ArrayAccess::offsetSet ====================== (PHP 5, PHP 7, PHP 8) ArrayAccess::offsetSet — Assign a value to the specified offset ### Description ``` public ArrayAccess::offsetSet(mixed $offset, mixed $value): void ``` Assigns a value to the specified offset. ### Parameters `offset` The offset to assign the value to. `value` The value to set. ### Return Values No value is returned. ### Notes > > **Note**: > > > The `offset` parameter will be set to **`null`** if another value is not available, like in the following example. > > > > ``` > <?php > $arrayaccess[] = "first value"; > $arrayaccess[] = "second value"; > print_r($arrayaccess); > ?> > ``` > The above example will output: > > > ``` > > Array > ( > [0] => first value > [1] => second value > ) > > ``` > > > **Note**: > > > This function is not called in assignments by reference and otherwise indirect changes to array dimensions overloaded with [ArrayAccess](class.arrayaccess) (indirect in the sense they are made not by changing the dimension directly, but by changing a sub-dimension or sub-property or assigning the array dimension by reference to another variable). Instead, [ArrayAccess::offsetGet()](arrayaccess.offsetget) is called. The operation will only be successful if that method returns by reference. > > php Memcached::getMulti Memcached::getMulti =================== (PECL memcached >= 0.1.0) Memcached::getMulti — Retrieve multiple items ### Description ``` public Memcached::getMulti(array $keys, int $flags = ?): mixed ``` **Memcached::getMulti()** is similar to [Memcached::get()](memcached.get), but instead of a single key item, it retrieves multiple items the keys of which are specified in the `keys` array. > > **Note**: > > > Before v3.0 a second argument `&cas_tokens` was in use. It was filled with the CAS token values for the found items. The `&cas_tokens` parameter was removed in v3.0 of the extension. It was replaced with a new flag **`Memcached::GET_EXTENDED`** that needs is to be used as the value for `flags`. > > The `flags` parameter can be used to specify additional options for **Memcached::getMulti()**. **`Memcached::GET_PRESERVE_ORDER`** ensures that the keys are returned in the same order as they were requested in. **`Memcached::GET_EXTENDED`** ensures that the CAS tokens will be fetched too. ### Parameters `keys` Array of keys to retrieve. `flags` The flags for the get operation. ### Return Values Returns the array of found items or **`false`** on failure. Use [Memcached::getResultCode()](memcached.getresultcode) if necessary. ### Changelog | Version | Description | | --- | --- | | PECL memcached 3.0.0 | The `&cas_tokens` parameter was removed. The **`Memcached::GET_EXTENDED`** was added and when passed as a flag it ensures the CAS tokens to be fetched. | ### Examples **Example #1 **Memcached::getMulti()** example for Memcached v3** ``` <?php // Valid for v3 of the extension $m = new Memcached(); $m->addServer('localhost', 11211); $items = array(     'key1' => 'value1',     'key2' => 'value2',     'key3' => 'value3' ); $m->setMulti($items); $result = $m->getMulti(array('key1', 'key3', 'badkey')); var_dump($result); ?> ``` The above example will output something similar to: ``` array(2) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" } ``` **Example #2 **Memcached::getMulti()** example for Memcached v1 and v2** ``` <?php // Valid for v1 and v2 of the extension $m = new Memcached(); $m->addServer('localhost', 11211); $items = array(     'key1' => 'value1',     'key2' => 'value2',     'key3' => 'value3' ); $m->setMulti($items); $result = $m->getMulti(array('key1', 'key3', 'badkey'), $cas); var_dump($result, $cas); ?> ``` The above example will output something similar to: ``` array(2) { ["key1"]=> string(6) "value1" ["key3"]=> string(6) "value3" } array(2) { ["key1"]=> float(2360) ["key3"]=> float(2362) } ``` **Example #3 **`Memcached::GET_PRESERVE_ORDER`** example for Memcached v3** ``` <?php // Valid for v3 of the extension $m = new Memcached(); $m->addServer('localhost', 11211); $data = array(     'foo' => 'foo-data',     'bar' => 'bar-data',     'baz' => 'baz-data',     'lol' => 'lol-data',     'kek' => 'kek-data', ); $m->setMulti($data, 3600); $keys = array_keys($data); $keys[] = 'zoo'; $got = $m->getMulti($keys, Memcached::GET_PRESERVE_ORDER); foreach ($got as $k => $v) {     echo "$k $v\n"; } ?> ``` The above example will output something similar to: ``` foo foo-data bar bar-data baz baz-data lol lol-data kek kek-data zoo ``` **Example #4 **`Memcached::GET_PRESERVE_ORDER`** example for Memcached v1 and v2** ``` <?php // Valid for v1 and v2 of the extension $m = new Memcached(); $m->addServer('localhost', 11211); $data = array(     'foo' => 'foo-data',     'bar' => 'bar-data',     'baz' => 'baz-data',     'lol' => 'lol-data',     'kek' => 'kek-data', ); $m->setMulti($data, 3600); $null = null; $keys = array_keys($data); $keys[] = 'zoo'; $got = $m->getMulti($keys, $null, Memcached::GET_PRESERVE_ORDER); foreach ($got as $k => $v) {     echo "$k $v\n"; } ?> ``` The above example will output something similar to: ``` foo foo-data bar bar-data baz baz-data lol lol-data kek kek-data zoo ``` ### See Also * [Memcached::getMultiByKey()](memcached.getmultibykey) - Retrieve multiple items from a specific server * [Memcached::get()](memcached.get) - Retrieve an item * [Memcached::getDelayed()](memcached.getdelayed) - Request multiple items php settype settype ======= (PHP 4, PHP 5, PHP 7, PHP 8) settype — Set the type of a variable ### Description ``` settype(mixed &$var, string $type): bool ``` Set the type of variable `var` to `type`. ### Parameters `var` The variable being converted. `type` Possibles values of `type` are: * "boolean" or "bool" * "integer" or "int" * "float" or "double" * "string" * "array" * "object" * "null" ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **settype()** example** ``` <?php $foo = "5bar"; // string $bar = true;   // boolean settype($foo, "integer"); // $foo is now 5   (integer) settype($bar, "string");  // $bar is now "1" (string) ?> ``` ### Notes > > **Note**: > > > Maximum value for "int" is **`PHP_INT_MAX`**. > > ### See Also * [gettype()](function.gettype) - Get the type of a variable * [type-casting](language.types.type-juggling#language.types.typecasting) * [type-juggling](language.types.type-juggling) php SolrQuery::removeHighlightField SolrQuery::removeHighlightField =============================== (PECL solr >= 0.9.2) SolrQuery::removeHighlightField — Removes one of the fields used for highlighting ### Description ``` public SolrQuery::removeHighlightField(string $field): SolrQuery ``` Removes one of the fields used for highlighting. ### Parameters `field` The name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. php ldap_delete ldap\_delete ============ (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_delete — Delete an entry from a directory ### Description ``` ldap_delete(LDAP\Connection $ldap, string $dn, ?array $controls = null): bool ``` Deletes a particular entry in LDAP directory. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `dn` The distinguished name of an LDAP entity. `controls` Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### See Also * [ldap\_delete\_ext()](function.ldap-delete-ext) - Delete an entry from a directory * [ldap\_add()](function.ldap-add) - Add entries to LDAP directory php Imagick::hasPreviousImage Imagick::hasPreviousImage ========================= (PECL imagick 2, PECL imagick 3) Imagick::hasPreviousImage — Checks if the object has a previous image ### Description ``` public Imagick::hasPreviousImage(): bool ``` Returns **`true`** if the object has more images when traversing the list in the reverse direction ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the object has more images when traversing the list in the reverse direction, returns **`false`** if there are none. php The php_user_filter class The php\_user\_filter class =========================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Children of this class are passed to [stream\_filter\_register()](function.stream-filter-register). Note that the [\_\_construct](language.oop5.decon#object.construct) method is not called; instead, [php\_user\_filter::onCreate()](php-user-filter.oncreate) should be used for initialization. Class synopsis -------------- class **php\_user\_filter** { /\* Properties \*/ public string [$filtername](class.php-user-filter#php-user-filter.props.filtername) = ""; public [mixed](language.types.declarations#language.types.declarations.mixed) [$params](class.php-user-filter#php-user-filter.props.params) = ""; public ?resource [$stream](class.php-user-filter#php-user-filter.props.stream) = null; /\* Methods \*/ public [\_\_construct](php-user-filter.construct)() ``` public filter( resource $in, resource $out, int &$consumed, bool $closing ): int ``` ``` public onClose(): void ``` ``` public onCreate(): bool ``` } Properties ---------- filtername Name of the filter registered by [stream\_filter\_append()](function.stream-filter-append). params stream Table of Contents ----------------- * [php\_user\_filter::\_\_construct](php-user-filter.construct) — Construct a new php\_user\_filter instance * [php\_user\_filter::filter](php-user-filter.filter) — Called when applying the filter * [php\_user\_filter::onClose](php-user-filter.onclose) — Called when closing the filter * [php\_user\_filter::onCreate](php-user-filter.oncreate) — Called when creating the filter
programming_docs
php mailparse_rfc822_parse_addresses mailparse\_rfc822\_parse\_addresses =================================== (PECL mailparse >= 0.9.0) mailparse\_rfc822\_parse\_addresses — Parse RFC 822 compliant addresses ### Description ``` mailparse_rfc822_parse_addresses(string $addresses): array ``` Parses a [» RFC 822](http://www.faqs.org/rfcs/rfc822) compliant recipient list, such as that found in the `To:` header. ### Parameters `addresses` A string containing addresses, like in: `Wez Furlong <[email protected]>, [email protected]` > > **Note**: > > > This string must not include the header name. > > ### Return Values Returns an array of associative arrays with the following keys for each recipient: | | | | --- | --- | | `display` | The recipient name, for display purpose. If this part is not set for a recipient, this key will hold the same value as `address`. | | `address` | The email address | | `is_group` | **`true`** if the recipient is a newsgroup, **`false`** otherwise. | ### Examples **Example #1 **mailparse\_rfc822\_parse\_addresses()** example** ``` <?php $to = 'Wez Furlong <[email protected]>, [email protected]'; var_dump(mailparse_rfc822_parse_addresses($to)); ?> ``` The above example will output: ``` array(2) { [0]=> array(3) { ["display"]=> string(11) "Wez Furlong" ["address"]=> string(15) "[email protected]" ["is_group"]=> bool(false) } [1]=> array(3) { ["display"]=> string(15) "[email protected]" ["address"]=> string(15) "[email protected]" ["is_group"]=> bool(false) } } ``` php convert_uudecode convert\_uudecode ================= (PHP 5, PHP 7, PHP 8) convert\_uudecode — Decode a uuencoded string ### Description ``` convert_uudecode(string $string): string|false ``` **convert\_uudecode()** decodes a uuencoded string. > **Note**: **convert\_uudecode()** neither accepts the `begin` nor the `end` line, which are part of uuencoded *files*. > > ### Parameters `string` The uuencoded data. ### Return Values Returns the decoded data as a string or **`false`** on failure. ### Examples **Example #1 **convert\_uudecode()** example** ``` <?php echo convert_uudecode("+22!L;W9E(%!(4\"$`\n`"); ?> ``` The above example will output: ``` I love PHP! ``` ### See Also * [convert\_uuencode()](function.convert-uuencode) - Uuencode a string php inotify_add_watch inotify\_add\_watch =================== (PECL inotify >= 0.1.2) inotify\_add\_watch — Add a watch to an initialized inotify instance ### Description ``` inotify_add_watch(resource $inotify_instance, string $pathname, int $mask): int ``` **inotify\_add\_watch()** adds a new watch or modify an existing watch for the file or directory specified in `pathname`. Using **inotify\_add\_watch()** on a watched object replaces the existing watch. Using the **`IN_MASK_ADD`** constant adds (OR) events to the existing watch. ### Parameters `inotify_instance` Resource returned by [inotify\_init()](function.inotify-init) `pathname` File or directory to watch `mask` Events to watch for. See [Predefined Constants](https://www.php.net/manual/en/inotify.constants.php). ### Return Values The return value is a unique (inotify instance wide) watch descriptor. ### See Also * [inotify\_init()](function.inotify-init) - Initialize an inotify instance php imap_mailboxmsginfo imap\_mailboxmsginfo ==================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_mailboxmsginfo — Get information about the current mailbox ### Description ``` imap_mailboxmsginfo(IMAP\Connection $imap): stdClass ``` Checks the current mailbox status on the server. It is similar to [imap\_status()](function.imap-status), but will additionally sum up the size of all messages in the mailbox, which will take some additional time to execute. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. ### Return Values Returns the information in an object with following properties: **Mailbox properties**| Date | date of last change (current datetime) | | Driver | driver | | Mailbox | name of the mailbox | | Nmsgs | number of messages | | Recent | number of recent messages | | Unread | number of unread messages | | Deleted | number of deleted messages | | Size | mailbox size | Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_mailboxmsginfo()** example** ``` <?php $mbox = imap_open("{imap.example.org}INBOX", "username", "password")       or die("can't connect: " . imap_last_error()); $check = imap_mailboxmsginfo($mbox); if ($check) {     echo "Date: "     . $check->Date    . "<br />\n" ;     echo "Driver: "   . $check->Driver  . "<br />\n" ;     echo "Mailbox: "  . $check->Mailbox . "<br />\n" ;     echo "Messages: " . $check->Nmsgs   . "<br />\n" ;     echo "Recent: "   . $check->Recent  . "<br />\n" ;     echo "Unread: "   . $check->Unread  . "<br />\n" ;     echo "Deleted: "  . $check->Deleted . "<br />\n" ;     echo "Size: "     . $check->Size    . "<br />\n" ; } else {     echo "imap_mailboxmsginfo() failed: " . imap_last_error() . "<br />\n"; } imap_close($mbox); ?> ``` php ParentIterator::hasChildren ParentIterator::hasChildren =========================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) ParentIterator::hasChildren — Check whether the inner iterator's current element has children ### Description ``` public ParentIterator::hasChildren(): bool ``` Check whether the inner iterator's current element has children. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php MessageFormatter::format MessageFormatter::format ======================== msgfmt\_format ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) MessageFormatter::format -- msgfmt\_format — Format the message ### Description Object-oriented style ``` public MessageFormatter::format(array $values): string|false ``` Procedural style ``` msgfmt_format(MessageFormatter $formatter, array $values): string|false ``` Format the message by substituting the data into the format string according to the locale rules ### Parameters `formatter` The message formatter `values` Arguments to insert into the format string ### Return Values The formatted string, or **`false`** if an error occurred ### Examples **Example #1 **msgfmt\_format()** example** ``` <?php $fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree"); echo msgfmt_format($fmt, array(4560, 123, 4560/123)); $fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum"); echo msgfmt_format($fmt, array(4560, 123, 4560/123)); ?> ``` **Example #2 OO example** ``` <?php $fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree"); echo $fmt->format(array(4560, 123, 4560/123)); $fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum"); echo $fmt->format(array(4560, 123, 4560/123)); ?> ``` The above example will output: ``` 4,560 monkeys on 123 trees make 37.073 monkeys per tree 4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum ``` ### See Also * [msgfmt\_create()](messageformatter.create) - Constructs a new Message Formatter * [msgfmt\_parse()](messageformatter.parse) - Parse input string according to pattern * [msgfmt\_format\_message()](messageformatter.formatmessage) - Quick format message * [msgfmt\_get\_error\_code()](messageformatter.geterrorcode) - Get the error code from last operation * [msgfmt\_get\_error\_message()](messageformatter.geterrormessage) - Get the error text from the last operation php tidy::$errorBuffer tidy::$errorBuffer ================== tidy\_get\_error\_buffer ======================== (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.5.2) tidy::$errorBuffer -- tidy\_get\_error\_buffer — Return warnings and errors which occurred parsing the specified document ### Description Object-oriented style (property): public string [$tidy->errorBuffer](tidy.props.errorbuffer); Procedural style: ``` tidy_get_error_buffer(tidy $tidy): string|false ``` Returns warnings and errors which occurred parsing the specified document. ### Parameters `tidy` The [Tidy](class.tidy) object. ### Return Values Returns the error buffer as a string, or **`false`** if the buffer is empty. ### Examples **Example #1 **tidy\_get\_error\_buffer()** example** ``` <?php $html = '<p>paragraph</p>'; $tidy = tidy_parse_string($html); echo tidy_get_error_buffer($tidy); /* or in OO: */ echo $tidy->errorBuffer; ?> ``` The above example will output: ``` line 1 column 1 - Warning: missing <!DOCTYPE> declaration line 1 column 1 - Warning: inserting missing 'title' element ``` ### See Also * [tidy\_access\_count()](function.tidy-access-count) - Returns the Number of Tidy accessibility warnings encountered for specified document * [tidy\_error\_count()](function.tidy-error-count) - Returns the Number of Tidy errors encountered for specified document * [tidy\_warning\_count()](function.tidy-warning-count) - Returns the Number of Tidy warnings encountered for specified document php ReflectionExtension::__clone ReflectionExtension::\_\_clone ============================== (PHP 5, PHP 7, PHP 8) ReflectionExtension::\_\_clone — Clones ### Description ``` private ReflectionExtension::__clone(): void ``` The clone method prevents an object from being cloned. Reflection objects cannot be cloned. ### Parameters This function has no parameters. ### Return Values No value is returned, if called a fatal error will occur. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | This method is no longer final. | ### See Also * [ReflectionExtension::\_\_construct()](reflectionextension.construct) - Constructs a ReflectionExtension * [Object cloning](language.oop5.cloning) php SolrInputDocument::getChildDocuments SolrInputDocument::getChildDocuments ==================================== (PECL solr >= 2.3.0) SolrInputDocument::getChildDocuments — Returns an array of child documents (SolrInputDocument) ### Description ``` public SolrInputDocument::getChildDocuments(): array ``` Returns an array of child documents (SolrInputDocument) ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrInputDocument::addChildDocument()](solrinputdocument.addchilddocument) - Adds a child document for block indexing * [SolrInputDocument::addChildDocuments()](solrinputdocument.addchilddocuments) - Adds an array of child documents * [SolrInputDocument::hasChildDocuments()](solrinputdocument.haschilddocuments) - Returns true if the document has any child documents * [SolrInputDocument::getChildDocumentsCount()](solrinputdocument.getchilddocumentscount) - Returns the number of child documents php The RecursiveCachingIterator class The RecursiveCachingIterator class ================================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) ... Class synopsis -------------- class **RecursiveCachingIterator** extends [CachingIterator](class.cachingiterator) implements [RecursiveIterator](class.recursiveiterator) { /\* Inherited constants \*/ public const int [CachingIterator::CALL\_TOSTRING](class.cachingiterator#cachingiterator.constants.call-tostring); public const int [CachingIterator::CATCH\_GET\_CHILD](class.cachingiterator#cachingiterator.constants.catch-get-child); public const int [CachingIterator::TOSTRING\_USE\_KEY](class.cachingiterator#cachingiterator.constants.tostring-use-key); public const int [CachingIterator::TOSTRING\_USE\_CURRENT](class.cachingiterator#cachingiterator.constants.tostring-use-current); public const int [CachingIterator::TOSTRING\_USE\_INNER](class.cachingiterator#cachingiterator.constants.tostring-use-inner); public const int [CachingIterator::FULL\_CACHE](class.cachingiterator#cachingiterator.constants.full-cache); /\* Methods \*/ public [\_\_construct](recursivecachingiterator.construct)([Iterator](class.iterator) `$iterator`, int `$flags` = RecursiveCachingIterator::CALL\_TOSTRING) ``` public getChildren(): ?RecursiveCachingIterator ``` ``` public hasChildren(): bool ``` /\* Inherited methods \*/ ``` public CachingIterator::count(): int ``` ``` public CachingIterator::current(): mixed ``` ``` public CachingIterator::getCache(): array ``` ``` public CachingIterator::getFlags(): int ``` ``` public CachingIterator::getInnerIterator(): Iterator ``` ``` public CachingIterator::hasNext(): bool ``` ``` public CachingIterator::key(): scalar ``` ``` public CachingIterator::next(): void ``` ``` public CachingIterator::offsetExists(string $key): bool ``` ``` public CachingIterator::offsetGet(string $key): mixed ``` ``` public CachingIterator::offsetSet(string $key, mixed $value): void ``` ``` public CachingIterator::offsetUnset(string $key): void ``` ``` public CachingIterator::rewind(): void ``` ``` public CachingIterator::setFlags(int $flags): void ``` ``` public CachingIterator::__toString(): string ``` ``` public CachingIterator::valid(): bool ``` ``` public IteratorIterator::current(): mixed ``` ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` ``` public IteratorIterator::key(): mixed ``` ``` public IteratorIterator::next(): void ``` ``` public IteratorIterator::rewind(): void ``` ``` public IteratorIterator::valid(): bool ``` } Table of Contents ----------------- * [RecursiveCachingIterator::\_\_construct](recursivecachingiterator.construct) — Construct * [RecursiveCachingIterator::getChildren](recursivecachingiterator.getchildren) — Return the inner iterator's children as a RecursiveCachingIterator * [RecursiveCachingIterator::hasChildren](recursivecachingiterator.haschildren) — Check whether the current element of the inner iterator has children php gmp_sub gmp\_sub ======== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_sub — Subtract numbers ### Description ``` gmp_sub(GMP|int|string $num1, GMP|int|string $num2): GMP ``` Subtracts `num2` from `num1` and returns the result. ### Parameters `num1` The number being subtracted from. A [GMP](class.gmp) object, an int or a numeric string. `num2` The number subtracted from `num1`. A [GMP](class.gmp) object, an int or a numeric string. ### Return Values A [GMP](class.gmp) object. ### Examples **Example #1 **gmp\_sub()** example** ``` <?php $sub = gmp_sub("281474976710656", "4294967296"); // 2^48 - 2^32 echo gmp_strval($sub) . "\n"; ?> ``` The above example will output: ``` 281470681743360 ``` php Yaf_View_Interface::assign Yaf\_View\_Interface::assign ============================ (Yaf >=1.0.0) Yaf\_View\_Interface::assign — Assign value to View engine ### Description ``` abstract public Yaf_View_Interface::assign(string $name, string $value = ?): bool ``` Assigan values to View engine, then the value can access directly by name in template. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `value` ### Return Values php pspell_store_replacement pspell\_store\_replacement ========================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) pspell\_store\_replacement — Store a replacement pair for a word ### Description ``` pspell_store_replacement(PSpell\Dictionary $dictionary, string $misspelled, string $correct): bool ``` **pspell\_store\_replacement()** stores a replacement pair for a word, so that replacement can be returned by [pspell\_suggest()](function.pspell-suggest) later. In order to be able to take advantage of this function, you have to use [pspell\_new\_personal()](function.pspell-new-personal) to open the dictionary. In order to permanently save the replacement pair, you have to use [pspell\_config\_personal()](function.pspell-config-personal) and [pspell\_config\_repl()](function.pspell-config-repl) to set the path where to save your custom wordlists, and then use [pspell\_save\_wordlist()](function.pspell-save-wordlist) for the changes to be written to disk. ### Parameters `dictionary` An [PSpell\Dictionary](class.pspell-dictionary) instance. `misspelled` The misspelled word. `correct` The fixed spelling for the `misspelled` word. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `dictionary` parameter expects an [PSpell\Dictionary](class.pspell-dictionary) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pspell\_store\_replacement()**** ``` <?php $pspell_config = pspell_config_create("en"); pspell_config_personal($pspell_config, "/var/dictionaries/custom.pws"); pspell_config_repl($pspell_config, "/var/dictionaries/custom.repl"); $pspell = pspell_new_config($pspell_config); pspell_store_replacement($pspell, $misspelled, $correct); pspell_save_wordlist($pspell); ?> ``` ### Notes > > **Note**: > > > This function will not work unless you have pspell .11.2 and aspell .32.5 or later. > > php Imagick::setImageFormat Imagick::setImageFormat ======================= (PECL imagick 2, PECL imagick 3) Imagick::setImageFormat — Sets the format of a particular image ### Description ``` public Imagick::setImageFormat(string $format): bool ``` Sets the format of a particular image in a sequence. ### Parameters `format` String presentation of the image format. Format support depends on the ImageMagick installation. ### Return Values Returns **`true`** on success. php openssl_x509_read openssl\_x509\_read =================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) openssl\_x509\_read — Parse an X.509 certificate and return an object for it ### Description ``` openssl_x509_read(OpenSSLCertificate|string $certificate): OpenSSLCertificate|false ``` **openssl\_x509\_read()** parses the certificate supplied by `certificate` and returns an [OpenSSLCertificate](class.opensslcertificate) object for it. ### Parameters `certificate` X509 certificate. See [Key/Certificate parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. ### Return Values Returns an [OpenSSLCertificate](class.opensslcertificate) on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was returned. | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | php SplMaxHeap::compare SplMaxHeap::compare =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplMaxHeap::compare — Compare elements in order to place them correctly in the heap while sifting up ### Description ``` protected SplMaxHeap::compare(mixed $value1, mixed $value2): int ``` Compare `value1` with `value2`. ### Parameters `value1` The value of the first node being compared. `value2` The value of the second node being compared. ### Return Values Result of the comparison, positive integer if `value1` is greater than `value2`, 0 if they are equal, negative integer otherwise. > > **Note**: > > > Having multiple elements with the same value in a Heap is not recommended. They will end up in an arbitrary relative position. > >
programming_docs
php Ds\Vector::map Ds\Vector::map ============== (PECL ds >= 1.0.0) Ds\Vector::map — Returns the result of applying a callback to each value ### Description ``` public Ds\Vector::map(callable $callback): Ds\Vector ``` Returns the result of applying a `callback` function to each value in the vector. ### Parameters `callback` ``` callback(mixed $value): mixed ``` A [callable](language.types.callable) to apply to each value in the vector. The callable should return what the new value will be in the new vector. ### Return Values The result of applying a `callback` to each value in the vector. > > **Note**: > > > The values of the current instance won't be affected. > > ### Examples **Example #1 **Ds\Vector::map()** example** ``` <?php $vector = new \Ds\Vector([1, 2, 3]); print_r($vector->map(function($value) { return $value * 2; })); print_r($vector); ?> ``` The above example will output something similar to: ``` Ds\Vector Object ( [0] => 2 [1] => 4 [2] => 6 ) Ds\Vector Object ( [0] => 1 [1] => 2 [2] => 3 ) ``` php openssl_random_pseudo_bytes openssl\_random\_pseudo\_bytes ============================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) openssl\_random\_pseudo\_bytes — Generate a pseudo-random string of bytes ### Description ``` openssl_random_pseudo_bytes(int $length, bool &$strong_result = null): string ``` Generates a string of pseudo-random bytes, with the number of bytes determined by the `length` parameter. It also indicates if a cryptographically strong algorithm was used to produce the pseudo-random bytes, and does this via the optional `strong_result` parameter. It's rare for this to be **`false`**, but some systems may be broken or old. ### Parameters `length` The length of the desired string of bytes. Must be a positive integer less than or equal to `2147483647`. PHP will try to cast this parameter to a non-null integer to use it. `strong_result` If passed into the function, this will hold a bool value that determines if the algorithm used was "cryptographically strong", e.g., safe for usage with GPG, passwords, etc. **`true`** if it did, otherwise **`false`** ### Return Values Returns the generated string of bytes. ### Errors/Exceptions **openssl\_random\_pseudo\_bytes()** throws an [Exception](class.exception) on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `strong_result` is nullable now. | | 7.4.0 | The function no longer returns **`false`** on failure, but throws an [Exception](class.exception) instead. | ### Examples **Example #1 **openssl\_random\_pseudo\_bytes()** example** ``` <?php for ($i = 1; $i <= 4; $i++) {     $bytes = openssl_random_pseudo_bytes($i, $cstrong);     $hex   = bin2hex($bytes);     echo "Lengths: Bytes: $i and Hex: " . strlen($hex) . PHP_EOL;     var_dump($hex);     var_dump($cstrong);     echo PHP_EOL; } ?> ``` The above example will output something similar to: ``` Lengths: Bytes: 1 and Hex: 2 string(2) "42" bool(true) Lengths: Bytes: 2 and Hex: 4 string(4) "dc6e" bool(true) Lengths: Bytes: 3 and Hex: 6 string(6) "288591" bool(true) Lengths: Bytes: 4 and Hex: 8 string(8) "ab86d144" bool(true) ``` ### See Also * [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php) - Get cryptographically secure random bytes * [bin2hex()](function.bin2hex) - Convert binary data into hexadecimal representation * [crypt()](function.crypt) - One-way string hashing * [random\_int()](https://www.php.net/manual/en/function.random-int.php) - Get a cryptographically secure, uniformly selected integer php Yaf_Registry::set Yaf\_Registry::set ================== (Yaf >=1.0.0) Yaf\_Registry::set — Add an item into registry ### Description ``` public static Yaf_Registry::set(string $name, string $value): bool ``` Add an item into registry ### Parameters `name` `value` ### Return Values php None Type Operators -------------- `instanceof` is used to determine whether a PHP variable is an instantiated object of a certain [class](language.oop5.basic#language.oop5.basic.class): **Example #1 Using `instanceof` with classes** ``` <?php class MyClass { } class NotMyClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof NotMyClass); ?> ``` The above example will output: ``` bool(true) bool(false) ``` `instanceof` can also be used to determine whether a variable is an instantiated object of a class that inherits from a parent class: **Example #2 Using `instanceof` with inherited classes** ``` <?php class ParentClass { } class MyClass extends ParentClass { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof ParentClass); ?> ``` The above example will output: ``` bool(true) bool(true) ``` To check if an object is *not* an instanceof a class, the [logical `not` operator](language.operators.logical) can be used. **Example #3 Using `instanceof` to check if object is *not* an instanceof a class** ``` <?php class MyClass { } $a = new MyClass; var_dump(!($a instanceof stdClass)); ?> ``` The above example will output: ``` bool(true) ``` Lastly, `instanceof` can also be used to determine whether a variable is an instantiated object of a class that implements an [interface](language.oop5.interfaces): **Example #4 Using `instanceof` with interfaces** ``` <?php interface MyInterface { } class MyClass implements MyInterface { } $a = new MyClass; var_dump($a instanceof MyClass); var_dump($a instanceof MyInterface); ?> ``` The above example will output: ``` bool(true) bool(true) ``` Although `instanceof` is usually used with a literal classname, it can also be used with another object or a string variable: **Example #5 Using `instanceof` with other variables** ``` <?php interface MyInterface { } class MyClass implements MyInterface { } $a = new MyClass; $b = new MyClass; $c = 'MyClass'; $d = 'NotMyClass'; var_dump($a instanceof $b); // $b is an object of class MyClass var_dump($a instanceof $c); // $c is a string 'MyClass' var_dump($a instanceof $d); // $d is a string 'NotMyClass' ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) ``` instanceof does not throw any error if the variable being tested is not an object, it simply returns **`false`**. Constants, however, were not allowed prior to PHP 7.3.0. **Example #6 Using `instanceof` to test other variables** ``` <?php $a = 1; $b = NULL; $c = imagecreate(5, 5); var_dump($a instanceof stdClass); // $a is an integer var_dump($b instanceof stdClass); // $b is NULL var_dump($c instanceof stdClass); // $c is a resource var_dump(FALSE instanceof stdClass); ?> ``` The above example will output: ``` bool(false) bool(false) bool(false) PHP Fatal error: instanceof expects an object instance, constant given ``` As of PHP 7.3.0, constants are allowed on the left-hand-side of the `instanceof` operator. **Example #7 Using `instanceof` to test constants** ``` <?php var_dump(FALSE instanceof stdClass); ?> ``` Output of the above example in PHP 7.3: ``` bool(false) ``` As of PHP 8.0.0, `instanceof` can now be used with arbitrary expressions. The expression must be wrapped in parentheses and produce a string. **Example #8 Using `instanceof` with an arbitrary expression** ``` <?php class ClassA extends \stdClass {} class ClassB extends \stdClass {} class ClassC extends ClassB {} class ClassD extends ClassA {} function getSomeClass(): string {     return ClassA::class; } var_dump(new ClassA instanceof ('std' . 'Class')); var_dump(new ClassB instanceof ('Class' . 'B')); var_dump(new ClassC instanceof ('Class' . 'A')); var_dump(new ClassD instanceof (getSomeClass())); ?> ``` Output of the above example in PHP 8: ``` bool(true) bool(true) bool(false) bool(true) ``` The `instanceof` operator has a functional variant with the [is\_a()](function.is-a) function. ### See Also * [get\_class()](function.get-class) * [is\_a()](function.is-a) php DirectoryIterator::getCTime DirectoryIterator::getCTime =========================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::getCTime — Get inode change time of the current DirectoryIterator item ### Description ``` public DirectoryIterator::getCTime(): int ``` Get the inode change time for the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values Returns the last change time of the file, as a Unix timestamp. ### Examples **Example #1 **DirectoryIterator::getCTime()** example** This example displays the file name and last change time of the files in the directory containing the script. ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); foreach ($iterator as $fileinfo) {     if ($fileinfo->isFile()) {         echo $fileinfo->getFilename() . " changed at " . $fileinfo->getCTime() . "\n";     } } ?> ``` The above example will output something similar to: ``` apple.jpg changed at 1240398312 banana.jpg changed at 1238605440 index.php changed at 1240398935 pear.jpg changed at 1237423740 ``` ### See Also * [DirectoryIterator::getATime()](directoryiterator.getatime) - Get last access time of the current DirectoryIterator item * [DirectoryIterator::getMTime()](directoryiterator.getmtime) - Get last modification time of current DirectoryIterator item * [filectime()](function.filectime) - Gets inode change time of file php socket_sendto socket\_sendto ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) socket\_sendto — Sends a message to a socket, whether it is connected or not ### Description ``` socket_sendto( Socket $socket, string $data, int $length, int $flags, string $address, ?int $port = null ): int|false ``` The function **socket\_sendto()** sends `length` bytes from `data` through the socket `socket` to the `port` at the address `address`. ### Parameters `socket` A [Socket](class.socket) instance created using [socket\_create()](function.socket-create). `data` The sent data will be taken from buffer `data`. `length` `length` bytes from `data` will be sent. `flags` The value of `flags` can be any combination of the following flags, joined with the binary OR (`|`) operator. **Possible values for `flags`**| **`MSG_OOB`** | Send OOB (out-of-band) data. | | **`MSG_EOR`** | Indicate a record mark. The sent data completes the record. | | **`MSG_EOF`** | Close the sender side of the socket and include an appropriate notification of this at the end of the sent data. The sent data completes the transaction. | | **`MSG_DONTROUTE`** | Bypass routing, use direct interface. | `address` IP address of the remote host. `port` `port` is the remote port number at which the data will be sent. ### Return Values **socket\_sendto()** returns the number of bytes sent to the remote host, or **`false`** if an error occurred. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | | 8.0.0 | `port` is nullable now. | ### Examples **Example #1 **socket\_sendto()** Example** ``` <?php     $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP);     $msg = "Ping !";     $len = strlen($msg);     socket_sendto($sock, $msg, $len, 0, '127.0.0.1', 1223);     socket_close($sock); ?> ``` ### See Also * [socket\_send()](function.socket-send) - Sends data to a connected socket php Yaf_Response_Abstract::getBody Yaf\_Response\_Abstract::getBody ================================ (Yaf >=1.0.0) Yaf\_Response\_Abstract::getBody — Retrieve a exists content ### Description ``` public Yaf_Response_Abstract::getBody(string $key = ?): mixed ``` Retrieve a exists content ### Parameters `key` the content key, if you don't specific, then Yaf\_Response\_Abstract::DEFAULT\_BODY will be used. if you pass in a **`null`**, then all contents will be returned as a array > > **Note**: > > > this parameter is introduced as of 2.2.0 > > ### Return Values ### Examples **Example #1 **Yaf\_Response\_Abstract::getBody()**example** ``` <?php $response = new Yaf_Response_Http(); $response->setBody("Hello")->setBody(" World", "footer"); var_dump($response->getBody()); //default  var_dump($response->getBody(Yaf_Response_Abstract::DEFAULT_BODY)); //same as above var_dump($response->getBody("footer")); var_dump($response->getBody(NULL)); //get all ?> ``` The above example will output something similar to: ``` string(5) "Hello" string(5) "Hello" string(6) " World" array(2) { ["content"]=> string(5) "Hello" ["footer"]=> string(6) " World" } ``` ### See Also * [Yaf\_Response\_Abstract::setBody()](yaf-response-abstract.setbody) - Set content to response * [Yaf\_Response\_Abstract::appendBody()](yaf-response-abstract.appendbody) - Append to response body * [Yaf\_Response\_Abstract::prependBody()](yaf-response-abstract.prependbody) - The prependBody purpose * [Yaf\_Response\_Abstract::clearBody()](yaf-response-abstract.clearbody) - Discard all exists response body php IntlDateFormatter::getCalendar IntlDateFormatter::getCalendar ============================== datefmt\_get\_calendar ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) IntlDateFormatter::getCalendar -- datefmt\_get\_calendar — Get the calendar type used for the IntlDateFormatter ### Description Object-oriented style ``` public IntlDateFormatter::getCalendar(): int|false ``` Procedural style ``` datefmt_get_calendar(IntlDateFormatter $formatter): int|false ``` ### Parameters `formatter` The formatter resource ### Return Values The [calendar type](class.intldateformatter#intl.intldateformatter-constants.calendartypes) being used by the formatter. Either **`IntlDateFormatter::TRADITIONAL`** or **`IntlDateFormatter::GREGORIAN`**. Returns **`false`** on failure. ### Examples **Example #1 **datefmt\_get\_calendar()** example** ``` <?php $fmt = datefmt_create(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'calendar of the formatter is : ' . datefmt_get_calendar($fmt); datefmt_set_calendar($fmt, IntlDateFormatter::TRADITIONAL); echo 'Now calendar of the formatter is : ' . datefmt_get_calendar($fmt); ?> ``` **Example #2 OO example** ``` <?php $fmt = new IntlDateFormatter(     'en_US',     IntlDateFormatter::FULL,     IntlDateFormatter::FULL,     'America/Los_Angeles',     IntlDateFormatter::GREGORIAN ); echo 'calendar of the formatter is : ' . $fmt->getCalendar(); $fmt->setCalendar(IntlDateFormatter::TRADITIONAL); echo 'Now calendar of the formatter is : ' . $fmt->getCalendar(); ?> ``` The above example will output: ``` calendar of the formatter is : 1 Now calendar of the formatter is : 0 ``` ### See Also * [datefmt\_get\_calendar\_object()](intldateformatter.getcalendarobject) - Get copy of formatterʼs calendar object * [datefmt\_set\_calendar()](intldateformatter.setcalendar) - Sets the calendar type used by the formatter * [datefmt\_create()](intldateformatter.create) - Create a date formatter php IntlChar::foldCase IntlChar::foldCase ================== (PHP 7, PHP 8) IntlChar::foldCase — Perform case folding on a code point ### Description ``` public static IntlChar::foldCase(int|string $codepoint, int $options = IntlChar::FOLD_CASE_DEFAULT): int|string|null ``` The given character is mapped to its case folding equivalent; if the character has no case folding equivalent, the character itself is returned. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) `options` Either **`IntlChar::FOLD_CASE_DEFAULT`** (default) or **`IntlChar::FOLD_CASE_EXCLUDE_SPECIAL_I`**. ### Return Values Returns the *Simple\_Case\_Folding* of the code point, if any; otherwise the code point itself on success, or **`null`** on failure. php DOMDocument::schemaValidate DOMDocument::schemaValidate =========================== (PHP 5, PHP 7, PHP 8) DOMDocument::schemaValidate — Validates a document based on a schema. Only XML Schema 1.0 is supported. ### Description ``` public DOMDocument::schemaValidate(string $filename, int $flags = 0): bool ``` Validates a document based on the given schema file. ### Parameters `filename` The path to the schema. `flags` A bitmask of Libxml schema validation flags. Currently the only supported value is [LIBXML\_SCHEMA\_CREATE](https://www.php.net/manual/en/libxml.constants.php). Available since Libxml 2.6.14. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [DOMDocument::schemaValidateSource()](domdocument.schemavalidatesource) - Validates a document based on a schema * [DOMDocument::relaxNGValidate()](domdocument.relaxngvalidate) - Performs relaxNG validation on the document * [DOMDocument::relaxNGValidateSource()](domdocument.relaxngvalidatesource) - Performs relaxNG validation on the document * [DOMDocument::validate()](domdocument.validate) - Validates the document based on its DTD php uopz_allow_exit uopz\_allow\_exit ================= (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_allow\_exit — Allows control over disabled exit opcode ### Description ``` uopz_allow_exit(bool $allow): void ``` By default uopz disables the exit opcode, so [exit()](function.exit) calls are practically ignored. **uopz\_allow\_exit()** allows to control this behavior. ### Parameters `allow` Whether to allow the execution of exit opcodes or not. ### Return Values No value is returned. ### Examples **Example #1 **uopz\_allow\_exit()** example** ``` <?php exit(1); echo 1; uopz_allow_exit(true); exit(2); echo 2; ?> ``` The above example will output: ``` 1 ``` ### Notes **Caution** [OPcache](https://www.php.net/manual/en/book.opcache.php) optimizes away dead code after unconditional exit. ### See Also * [uopz\_get\_exit\_status()](function.uopz-get-exit-status) - Retrieve the last set exit status php utf8_encode utf8\_encode ============ (PHP 4, PHP 5, PHP 7, PHP 8) utf8\_encode — Converts a string from ISO-8859-1 to UTF-8 **Warning**This function has been *DEPRECATED* as of PHP 8.2.0. Relying on this function is highly discouraged. ### Description ``` utf8_encode(string $string): string ``` This function converts the string `string` from the `ISO-8859-1` encoding to `UTF-8`. > > **Note**: > > > This function does not attempt to guess the current encoding of the provided string, it assumes it is encoded as ISO-8859-1 (also known as "Latin 1") and converts to UTF-8. Since every sequence of bytes is a valid ISO-8859-1 string, this never results in an error, but will not result in a useful string if a different encoding was intended. > > Many web pages marked as using the `ISO-8859-1` character encoding actually use the similar `Windows-1252` encoding, and web browsers will interpret `ISO-8859-1` web pages as `Windows-1252`. `Windows-1252` features additional printable characters, such as the Euro sign (`€`) and curly quotes (`“` `”`), instead of certain `ISO-8859-1` control characters. This function will not convert such `Windows-1252` characters correctly. Use a different function if `Windows-1252` conversion is required. > > ### Parameters `string` An ISO-8859-1 string. ### Return Values Returns the UTF-8 translation of `string`. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | This function has been deprecated. | | 7.2.0 | This function has been moved from the XML extension to the core of PHP. In previous versions, it was only available if the XML extension was installed. | ### Examples **Example #1 Basic example** ``` <?php // Convert the string 'Zoë' from ISO 8859-1 to UTF-8 $iso8859_1_string = "\x5A\x6F\xEB"; $utf8_string = utf8_encode($iso8859_1_string); echo bin2hex($utf8_string), "\n"; ?> ``` The above example will output: ``` 5a6fc3ab ``` ### See Also * [utf8\_decode()](function.utf8-decode) - Converts a string from UTF-8 to ISO-8859-1, replacing invalid or unrepresentable characters * [mb\_convert\_encoding()](function.mb-convert-encoding) - Convert a string from one character encoding to another * [UConverter::transcode()](uconverter.transcode) - Convert a string from one character encoding to another * [iconv()](function.iconv) - Convert a string from one character encoding to another
programming_docs
php imap_search imap\_search ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_search — This function returns an array of messages matching the given search criteria ### Description ``` imap_search( IMAP\Connection $imap, string $criteria, int $flags = SE_FREE, string $charset = "" ): array|false ``` This function performs a search on the mailbox currently opened in the given IMAP stream. For example, to match all unanswered messages sent by Mom, you'd use: "UNANSWERED FROM mom". Searches appear to be case insensitive. This list of criteria is from a reading of the UW c-client source code and may be incomplete or inaccurate (see also [» RFC1176](http://www.faqs.org/rfcs/rfc1176), section "tag SEARCH search\_criteria"). ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `criteria` A string, delimited by spaces, in which the following keywords are allowed. Any multi-word arguments (e.g. `FROM "joey smith"`) must be quoted. Results will match all `criteria` entries. * ALL - return all messages matching the rest of the criteria * ANSWERED - match messages with the \\ANSWERED flag set * BCC "string" - match messages with "string" in the Bcc: field * BEFORE "date" - match messages with Date: before "date" * BODY "string" - match messages with "string" in the body of the message * CC "string" - match messages with "string" in the Cc: field * DELETED - match deleted messages * FLAGGED - match messages with the \\FLAGGED (sometimes referred to as Important or Urgent) flag set * FROM "string" - match messages with "string" in the From: field * KEYWORD "string" - match messages with "string" as a keyword * NEW - match new messages * OLD - match old messages * ON "date" - match messages with Date: matching "date" * RECENT - match messages with the \\RECENT flag set * SEEN - match messages that have been read (the \\SEEN flag is set) * SINCE "date" - match messages with Date: after "date" * SUBJECT "string" - match messages with "string" in the Subject: * TEXT "string" - match messages with text "string" * TO "string" - match messages with "string" in the To: * UNANSWERED - match messages that have not been answered * UNDELETED - match messages that are not deleted * UNFLAGGED - match messages that are not flagged * UNKEYWORD "string" - match messages that do not have the keyword "string" * UNSEEN - match messages which have not been read yet `flags` Valid values for `flags` are **`SE_UID`**, which causes the returned array to contain UIDs instead of messages sequence numbers. `charset` MIME character set to use when searching strings. ### Return Values Returns an array of message numbers or UIDs. Return **`false`** if it does not understand the search `criteria` or no messages have been found. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_search()** example** ``` <?php $imap   = imap_open('{imap.example.com:993/imap/ssl}INBOX', '[email protected]', 'pass123', OP_READONLY); $some   = imap_search($imap, 'SUBJECT "HOWTO be Awesome" SINCE "8 August 2008"', SE_UID); $msgnos = imap_search($imap, 'ALL'); $uids   = imap_search($imap, 'ALL', SE_UID); print_r($some); print_r($msgnos); print_r($uids); ?> ``` The above example will output something similar to: ``` Array ( [0] => 4 [1] => 6 [2] => 11 ) Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) Array ( [0] => 1 [1] => 4 [2] => 6 [3] => 8 [4] => 11 [5] => 12 ) ``` ### See Also * [imap\_listscan()](function.imap-listscan) - Returns the list of mailboxes that matches the given text php grapheme_strlen grapheme\_strlen ================ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) grapheme\_strlen — Get string length in grapheme units ### Description Procedural style ``` grapheme_strlen(string $string): int|false|null ``` Get string length in grapheme units (not bytes or characters) ### Parameters `string` The string being measured for length. It must be a valid UTF-8 string. ### Return Values The length of the string on success, or **`false`** on failure. ### Examples **Example #1 **grapheme\_strlen()** example** ``` <?php $char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D" $char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D" print grapheme_strlen( 'abc' . $char_a_ring_nfd . $char_o_diaeresis_nfd . $char_a_ring_nfd); ?> ``` The above example will output: ``` 6 ``` ### See Also * [» Unicode Text Segmentation: Grapheme Cluster Boundaries](http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries) * [iconv\_strlen()](function.iconv-strlen) - Returns the character count of string * [mb\_strlen()](function.mb-strlen) - Get string length * [strlen()](function.strlen) - Get string length php Phar::stopBuffering Phar::stopBuffering =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) Phar::stopBuffering — Stop buffering write requests to the Phar archive, and save changes to disk ### Description ``` public Phar::stopBuffering(): void ``` **Phar::stopBuffering()** is used in conjunction with the [Phar::startBuffering()](phar.startbuffering) method. [Phar::startBuffering()](phar.startbuffering) can provide a significant performance boost when creating or modifying a Phar archive with a large number of files. Ordinarily, every time a file within a Phar archive is created or modified in any way, the entire Phar archive will be recreated with the changes. In this way, the archive will be up-to-date with the activity performed on it. However, this can be unnecessary when simply creating a new Phar archive, when it would make more sense to write the entire archive out at once. Similarly, it is often necessary to make a series of changes and to ensure that they all are possible before making any changes on disk, similar to the relational database concept of transactions. The [Phar::startBuffering()](phar.startbuffering)/**Phar::stopBuffering()** pair of methods is provided for this purpose. Phar write buffering is per-archive, buffering active for the `foo.phar` Phar archive does not affect changes to the `bar.phar` Phar archive. ### Parameters This function has no parameters. ### Return Values No value is returned. ### Errors/Exceptions [PharException](class.pharexception) is thrown if any problems are encountered flushing changes to disk. ### Examples **Example #1 A **Phar::stopBuffering()** example** ``` <?php $p = new Phar(dirname(__FILE__) . '/brandnewphar.phar', 0, 'brandnewphar.phar'); $p['file1.txt'] = 'hi'; $p->startBuffering(); var_dump($p->getStub()); $p->setStub("<?php function __autoload(\$class) {     include 'phar://brandnewphar.phar/' . str_replace('_', '/', \$class) . '.php'; } Phar::mapPhar('brandnewphar.phar'); include 'phar://brandnewphar.phar/startup.php'; __HALT_COMPILER();"); $p->stopBuffering(); var_dump($p->getStub()); ?> ``` The above example will output: ``` string(24) "<?php __HALT_COMPILER();" string(195) "<?php function __autoload($class) { include 'phar://' . str_replace('_', '/', $class); } Phar::mapPhar('brandnewphar.phar'); include 'phar://brandnewphar.phar/startup.php'; __HALT_COMPILER();" ``` ### See Also * [Phar::startBuffering()](phar.startbuffering) - Start buffering Phar write operations, do not modify the Phar object on disk * [Phar::isBuffering()](phar.isbuffering) - Used to determine whether Phar write operations are being buffered, or are flushing directly to disk php ldap_mod_add ldap\_mod\_add ============== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_mod\_add — Add attribute values to current attributes ### Description ``` ldap_mod_add( LDAP\Connection $ldap, string $dn, array $entry, ?array $controls = null ): bool ``` Adds one or more attribute values to the specified `dn`. To add a whole new object see [ldap\_add()](function.ldap-add) function. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `dn` The distinguished name of an LDAP entity. `entry` An associative array listing the attirbute values to add. If an attribute was not existing yet it will be added. If an attribute is existing you can only add values to it if it supports multiple values. `controls` Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### Notes > **Note**: This function is binary-safe. > > ### See Also * [ldap\_mod\_add\_ext()](function.ldap-mod_add-ext) - Add attribute values to current attributes * [ldap\_mod\_del()](function.ldap-mod-del) - Delete attribute values from current attributes * [ldap\_mod\_replace()](function.ldap-mod-replace) - Replace attribute values with new ones * [ldap\_modify\_batch()](function.ldap-modify-batch) - Batch and execute modifications on an LDAP entry php GearmanJob::unique GearmanJob::unique ================== (PECL gearman >= 0.5.0) GearmanJob::unique — Get the unique identifier ### Description ``` public GearmanJob::unique(): string ``` Returns the unique identifier for this job. The identifier is assigned by the client. ### Parameters This function has no parameters. ### Return Values An opaque unique identifier. ### See Also * [GearmanClient::do()](gearmanclient.do) - Run a single task and return a result [deprecated] * [GearmanTask::uuid()](gearmantask.uuid) - Get the unique identifier for a task (deprecated) php Imagick::getSizeOffset Imagick::getSizeOffset ====================== (PECL imagick 2, PECL imagick 3) Imagick::getSizeOffset — Returns the size offset ### Description ``` public Imagick::getSizeOffset(): int ``` Returns the size offset associated with the Imagick object. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters This function has no parameters. ### Return Values Returns the size offset associated with the Imagick object. ### Errors/Exceptions Throws ImagickException on error. php ImagickDraw::getClipUnits ImagickDraw::getClipUnits ========================= (PECL imagick 2, PECL imagick 3) ImagickDraw::getClipUnits — Returns the interpretation of clip path units ### Description ``` public ImagickDraw::getClipUnits(): int ``` **Warning**This function is currently not documented; only its argument list is available. Returns the interpretation of clip path units. ### Return Values Returns an int on success. php ImagickPixel::getColorValueQuantum ImagickPixel::getColorValueQuantum ================================== (PECL imagick 2 >= 2.3.0, PECL imagick 3) ImagickPixel::getColorValueQuantum — Description ### Description ``` public ImagickPixel::getColorValueQuantum(int $color): int|float ``` Gets the quantum value of a color in the ImagickPixel. Return value is a float if ImageMagick was compiled with HDRI, otherwise an integer. ### Parameters This function has no parameters. ### Return Values The quantum value of the color element. Float if ImageMagick was compiled with HDRI, otherwise an int. ### Examples **Example #1 **ImagickPixel::getColorValueQuantum()**** ``` <?php         $color = new \ImagickPixel('rgb(128, 5, 255)');         $colorRed = $color->getColorValueQuantum(\Imagick::COLOR_RED);         $colorGreen = $color->getColorValueQuantum(\Imagick::COLOR_GREEN);         $colorBlue = $color->getColorValueQuantum(\Imagick::COLOR_BLUE);         $colorAlpha = $color->getColorValueQuantum(\Imagick::COLOR_ALPHA);         printf(             "Red: %s Green: %s  Blue %s Alpha: %s",             $colorRed,             $colorGreen,             $colorBlue,             $colorAlpha         ); ?> ``` php imap_list imap\_list ========== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_list — Read the list of mailboxes ### Description ``` imap_list(IMAP\Connection $imap, string $reference, string $pattern): array|false ``` Read the list of mailboxes. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `reference` `reference` should normally be just the server specification as described in [imap\_open()](function.imap-open). **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `pattern` Specifies where in the mailbox hierarchy to start searching. There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory. ### Return Values Returns an array containing the names of the mailboxes or **`false`** in case of failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_list()** example** ``` <?php $mbox = imap_open("{imap.example.org}", "username", "password", OP_HALFOPEN)       or die("can't connect: " . imap_last_error()); $list = imap_list($mbox, "{imap.example.org}", "*"); if (is_array($list)) {     foreach ($list as $val) {         echo imap_utf7_decode($val) . "\n";     } } else {     echo "imap_list failed: " . imap_last_error() . "\n"; } imap_close($mbox); ?> ``` ### See Also * [imap\_getmailboxes()](function.imap-getmailboxes) - Read the list of mailboxes, returning detailed information on each one * [imap\_lsub()](function.imap-lsub) - List all the subscribed mailboxes php shm_attach shm\_attach =========== (PHP 4, PHP 5, PHP 7, PHP 8) shm\_attach — Creates or open a shared memory segment ### Description ``` shm_attach(int $key, ?int $size = null, int $permissions = 0666): SysvSharedMemory|false ``` **shm\_attach()** returns an id that can be used to access the System V shared memory with the given `key`, the first call creates the shared memory segment with `size` and the optional perm-bits `permissions`. A second call to **shm\_attach()** for the same `key` will return a different [SysvSharedMemory](class.sysvsharedmemory) instance, but both instances access the same underlying shared memory. `size` and `permissions` will be ignored. ### Parameters `key` A numeric shared memory segment ID `size` The memory size. If not provided, default to the `sysvshm.init_mem` in the php.ini, otherwise 10000 bytes. `permissions` The optional permission bits. Default to 0666. ### Return Values Returns a [SysvSharedMemory](class.sysvsharedmemory) instance on success, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns an [SysvSharedMemory](class.sysvsharedmemory) instance now; previously, a resource was returned. | | 8.0.0 | `size` is nullable now. | ### See Also * [shm\_detach()](function.shm-detach) - Disconnects from shared memory segment * [ftok()](function.ftok) - Convert a pathname and a project identifier to a System V IPC key php Yaf_Config_Simple::rewind Yaf\_Config\_Simple::rewind =========================== (Yaf >=1.0.0) Yaf\_Config\_Simple::rewind — The rewind purpose ### Description ``` public Yaf_Config_Simple::rewind(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php SolrQuery::getGroupNGroups SolrQuery::getGroupNGroups ========================== (PECL solr >= 2.2.0) SolrQuery::getGroupNGroups — Returns the group.ngroups value ### Description ``` public SolrQuery::getGroupNGroups(): bool ``` Returns the group.ngroups value ### Parameters This function has no parameters. ### Return Values ### See Also * [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results php parse_ini_file parse\_ini\_file ================ (PHP 4, PHP 5, PHP 7, PHP 8) parse\_ini\_file — Parse a configuration file ### Description ``` parse_ini_file(string $filename, bool $process_sections = false, int $scanner_mode = INI_SCANNER_NORMAL): array|false ``` **parse\_ini\_file()** loads in the ini file specified in `filename`, and returns the settings in it in an associative array. The structure of the ini file is the same as the php.ini's. ### Parameters `filename` The filename of the ini file being parsed. If a relative path is used, it is evaluated relative to the current working directory, then the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path). `process_sections` By setting the `process_sections` parameter to **`true`**, you get a multidimensional array, with the section names and settings included. The default for `process_sections` is **`false`** `scanner_mode` Can either be **`INI_SCANNER_NORMAL`** (default) or **`INI_SCANNER_RAW`**. If **`INI_SCANNER_RAW`** is supplied, then option values will not be parsed. As of PHP 5.6.1 can also be specified as **`INI_SCANNER_TYPED`**. In this mode boolean, null and integer types are preserved when possible. String values `"true"`, `"on"` and `"yes"` are converted to **`true`**. `"false"`, `"off"`, `"no"` and `"none"` are considered **`false`**. `"null"` is converted to **`null`** in typed mode. Also, all numeric strings are converted to integer type if it is possible. ### Return Values The settings are returned as an associative array on success, and **`false`** on failure. ### Examples **Example #1 Contents of sample.ini** ``` ; This is a sample configuration file ; Comments start with ';', as in php.ini [first_section] one = 1 five = 5 animal = BIRD [second_section] path = "/usr/local/bin" URL = "http://www.example.com/~username" [third_section] phpversion[] = "5.0" phpversion[] = "5.1" phpversion[] = "5.2" phpversion[] = "5.3" urls[svn] = "http://svn.php.net" urls[git] = "http://git.php.net" ``` **Example #2 **parse\_ini\_file()** example** [Constants](language.constants) (but not "magic constants" like **`__FILE__`**) may also be parsed in the ini file so if you define a constant as an ini value before running **parse\_ini\_file()**, it will be integrated into the results. Only ini values are evaluated, and the value must be just the constant. For example: ``` <?php define('BIRD', 'Dodo bird'); // Parse without sections $ini_array = parse_ini_file("sample.ini"); print_r($ini_array); // Parse with sections $ini_array = parse_ini_file("sample.ini", true); print_r($ini_array); ?> ``` The above example will output something similar to: ``` Array ( [one] => 1 [five] => 5 [animal] => Dodo bird [path] => /usr/local/bin [URL] => http://www.example.com/~username [phpversion] => Array ( [0] => 5.0 [1] => 5.1 [2] => 5.2 [3] => 5.3 ) [urls] => Array ( [svn] => http://svn.php.net [git] => http://git.php.net ) ) Array ( [first_section] => Array ( [one] => 1 [five] => 5 [animal] => Dodo bird ) [second_section] => Array ( [path] => /usr/local/bin [URL] => http://www.example.com/~username ) [third_section] => Array ( [phpversion] => Array ( [0] => 5.0 [1] => 5.1 [2] => 5.2 [3] => 5.3 ) [urls] => Array ( [svn] => http://svn.php.net [git] => http://git.php.net ) ) ) ``` **Example #3 **parse\_ini\_file()** parsing a php.ini file** ``` <?php // A simple function used for comparing the results below function yesno($expression) {     return($expression ? 'Yes' : 'No'); } // Get the path to php.ini using the php_ini_loaded_file() function $ini_path = php_ini_loaded_file(); // Parse php.ini $ini = parse_ini_file($ini_path); // Print and compare the values, note that using get_cfg_var() // will give the same results for parsed and loaded here echo '(parsed) magic_quotes_gpc = ' . yesno($ini['magic_quotes_gpc']) . PHP_EOL; echo '(loaded) magic_quotes_gpc = ' . yesno(get_cfg_var('magic_quotes_gpc')) . PHP_EOL; ?> ``` The above example will output something similar to: ``` (parsed) magic_quotes_gpc = Yes (loaded) magic_quotes_gpc = Yes ``` **Example #4 Value Interpolation** In addition to evaluating constants, certain characters have special meaning in an ini value. Additionally, environment variables and previously defined configuration options (see [get\_cfg\_var()](function.get-cfg-var)) may be read using `${}` syntax. ``` ; | is used for bitwise OR three = 2|3 ; & is used for bitwise AND four = 6&5 ; ^ is used for bitwise XOR five = 3^6 ; ~ is used for bitwise negate negative_two = ~1 ; () is used for grouping seven = (8|7)&(6|5) ; Interpolate the PATH environment variable path = ${PATH} ; Interpolate the configuration option 'memory_limit' configured_memory_limit = ${memory_limit} ``` **Example #5 Escaping Characters** Some characters have special meaning in double-quoted strings and must be escaped by the backslash prefix. First of all, these are the double quote `"` as the boundary marker, and the backslash `\` itself (if followed by one of the special characters): ``` quoted = "She said \"Exactly my point\"." ; Results in a string with quote marks in it. hint = "Use \\\" to escape double quote" ; Results in: Use \" to escape double quote ``` There is an exception made for Windows-like paths: it's possible to not escape trailing backslash if the quoted string is directly followed by a linebreak: ``` save_path = "C:\Temp\" ``` If one does need to escape double quote followed by linebreak in a multiline value, it's possible to use value concatenation in the following way (there is one double-quoted string directly followed by another one): ``` long_text = "Lorem \"ipsum\""" dolor" ; Results in: Lorem "ipsum"\n dolor ``` Another character with special meaning is `$` (the dollar sign). It must be escaped if followed by the open curly brace: ``` code = "\${test}" ``` Escaping characters is not supported in the **`INI_SCANNER_RAW`** mode (in this mode all characters are processed "as is"). Note that the ini parser doesn't support standard escape sequences (`\n`, `\t`, etc.). If necessary, post-process the result of **parse\_ini\_file()** with [stripcslashes()](function.stripcslashes) function. ### Notes > > **Note**: > > > This function has nothing to do with the php.ini file. It is already processed by the time you run your script. This function can be used to read in your own application's configuration files. > > > > **Note**: > > > If a value in the ini file contains any non-alphanumeric characters it needs to be enclosed in double-quotes ("). > > > **Note**: There are reserved words which must not be used as keys for ini files. These include: `null`, `yes`, `no`, `true`, `false`, `on`, `off`, `none`. Values `null`, `off`, `no` and `false` result in `""`, and values `on`, `yes` and `true` result in `"1"`, unless **`INI_SCANNER_TYPED`** mode is used. Characters `?{}|&~!()^"` must not be used anywhere in the key and have a special meaning in the value. > > > > **Note**: > > > Entries without an equal sign are ignored. For example, "foo" is ignored whereas "bar =" is parsed and added with an empty value. For example, MySQL has a "no-auto-rehash" setting in my.cnf that does not take a value, so it is ignored. > > > > **Note**: > > > ini files are generally treated as plain text by web servers and thus served to browsers if requested. That means for security you must either keep your ini files outside of your docroot or reconfigure your web server to not serve them. Failure to do either of those may introduce a security risk. > > ### See Also * [parse\_ini\_string()](function.parse-ini-string) - Parse a configuration string
programming_docs
php sodium_crypto_kx_keypair sodium\_crypto\_kx\_keypair =========================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_kx\_keypair — Creates a new sodium keypair ### Description ``` sodium_crypto_kx_keypair(): string ``` Create a new sodium keypair consisting of the secret key (32 bytes) followed by the public key (32 bytes). The keys can be retrieved by calling [sodium\_crypto\_kx\_secretkey()](function.sodium-crypto-kx-secretkey) and [sodium\_crypto\_kx\_publickey()](function.sodium-crypto-kx-publickey), respectively. ### Parameters This function has no parameters. ### Return Values Returns the new keypair on success; throws an exception otherwise. ### Examples **Example #1 **sodium\_crypto\_kx\_keypair()** usage** Create a new keypair and retrieve the secret and the public key from it. ``` <?php $keypair = sodium_crypto_kx_keypair(); $secret = sodium_crypto_kx_secretkey($keypair); $public = sodium_crypto_kx_publickey($keypair); printf("secret: %s\npublic: %s", sodium_bin2hex($secret), sodium_bin2hex($public)); ?> ``` The above example will output something similar to: ``` secret: e7c5c918fdc40762e6000542c0118f4368ce8fd242b0e48c1e17202797a25daf public: d1f59fda8652caf40ed1a01d2b6f3802b60846986372cd8fa337b7c12c428b18 ``` php Imagick::commentImage Imagick::commentImage ===================== (PECL imagick 2, PECL imagick 3) Imagick::commentImage — Adds a comment to your image ### Description ``` public Imagick::commentImage(string $comment): bool ``` Adds a comment to your image. ### Parameters `comment` The comment to add ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::commentImage()**:** Commenting an image and retrieving the comment: ``` <?php /* Create new Imagick object */ $im = new imagick(); /* Create an empty image */ $im->newImage(100, 100, new ImagickPixel("red")); /* Add comment to the image */ $im->commentImage("Hello World!"); /* Display the comment */ echo $im->getImageProperty("comment"); ?> ``` php geoip_time_zone_by_country_and_region geoip\_time\_zone\_by\_country\_and\_region =========================================== (PECL geoip >= 1.0.4) geoip\_time\_zone\_by\_country\_and\_region — Returns the time zone for some country and region code combo ### Description ``` geoip_time_zone_by_country_and_region(string $country_code, string $region_code = ?): string ``` The **geoip\_time\_zone\_by\_country\_and\_region()** function will return the time zone corresponding to a country and region code combo. In the United States, the region code corresponds to the two-letter abbreviation of each state. In Canada, the region code corresponds to the two-letter province or territory code as attributed by Canada Post. For the rest of the world, GeoIP uses FIPS 10-4 codes to represent regions. You can check [» http://www.maxmind.com/app/fips10\_4](http://www.maxmind.com/app/fips10_4) for a detailed list of FIPS 10-4 codes. This function is always available if using GeoIP Library version 1.4.1 or newer. The data is taken directly from the GeoIP Library and not from any database. ### Parameters `country_code` The two-letter country code (see [geoip\_country\_code\_by\_name()](function.geoip-country-code-by-name)) `region_code` The two-letter (or digit) region code (see [geoip\_region\_by\_name()](function.geoip-region-by-name)) ### Return Values Returns the time zone on success, or **`false`** if the country and region code combo cannot be found. ### Examples **Example #1 A **geoip\_time\_zone\_by\_country\_and\_region()** example using region code for US/Canada** This will print the time zone for country CA (Canada), region QC (Quebec). ``` <?php $timezone = geoip_time_zone_by_country_and_region('CA', 'QC'); if ($timezone) {     echo 'Time zone for CA/QC is: ' . $timezone; } ?> ``` The above example will output: ``` Time zone for CA/QC is: America/Montreal ``` **Example #2 A **geoip\_time\_zone\_by\_country\_and\_region()** example using FIPS codes** This will print the time zone for country JP (Japan), region 01 (Aichi). ``` <?php $timezone = geoip_time_zone_by_country_and_region('JP', '01'); if ($timezone) {     echo 'Time zone for JP/01 is: ' . $timezone; } ?> ``` The above example will output: ``` Time zone for JP/01 is: Asia/Tokyo ``` php ImagickPixel::setColorValue ImagickPixel::setColorValue =========================== (PECL imagick 2, PECL imagick 3) ImagickPixel::setColorValue — Sets the normalized value of one of the channels ### Description ``` public ImagickPixel::setColorValue(int $color, float $value): bool ``` Sets the value of the specified channel of this object to the provided value, which should be between 0 and 1. This function can be used to provide an opacity channel to an ImagickPixel object. ### Parameters `color` One of the Imagick color constants e.g. \Imagick::COLOR\_GREEN or \Imagick::COLOR\_ALPHA. `value` The value to set this channel to, ranging from 0 to 1. ### Return Values Returns **`true`** on success. ### Examples **Example #1 Basic **Imagick::setColorValue()** usage** ``` <?php $color  = new \ImagickPixel('firebrick'); $color->setColorValue(Imagick::COLOR_ALPHA, 0.5); print_r($color->getcolor(true)); ?> ``` The above example will output: ``` Array ( [r] => 0.69803921568627 [g] => 0.13333333333333 [b] => 0.13333333333333 [a] => 0.50000762951095 ) ``` php NumberFormatter::getErrorMessage NumberFormatter::getErrorMessage ================================ numfmt\_get\_error\_message =========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::getErrorMessage -- numfmt\_get\_error\_message — Get formatter's last error message ### Description Object-oriented style ``` public NumberFormatter::getErrorMessage(): string ``` Procedural style ``` numfmt_get_error_message(NumberFormatter $formatter): string ``` Get error message from the last function performed by the formatter. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. ### Return Values Returns error message from last formatter call. ### Examples **Example #1 **numfmt\_get\_error\_message()** example** ``` <?php $fmt = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); $data = numfmt_format($fmt, 1234567.891234567890000); var_dump(numfmt_get_error_message($fmt)); ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); $fmt->format(1234567.891234567890000); var_dump(numfmt_get_error_message($fmt)); ?> ``` ### See Also * [numfmt\_get\_error\_code()](numberformatter.geterrorcode) - Get formatter's last error code * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure php RecursiveCallbackFilterIterator::__construct RecursiveCallbackFilterIterator::\_\_construct ============================================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) RecursiveCallbackFilterIterator::\_\_construct — Create a RecursiveCallbackFilterIterator from a RecursiveIterator ### Description public **RecursiveCallbackFilterIterator::\_\_construct**([RecursiveIterator](class.recursiveiterator) `$iterator`, [callable](language.types.callable) `$callback`) Creates a filtered iterator from a [RecursiveIterator](class.recursiveiterator) using the `callback` to determine which items are accepted or rejected. ### Parameters `iterator` The recursive iterator to be filtered. `callback` The callback, which should return **`true`** to accept the current item or **`false`** otherwise. See [Examples](class.recursivecallbackfilteriterator#recursivecallbackfilteriterator.examples). May be any valid [callable](language.types.callable) value. ### See Also * [RecursiveCallbackFilterIterator Examples](class.recursivecallbackfilteriterator#recursivecallbackfilteriterator.examples) * [RecursiveCallbackFilterIterator::getChildren()](recursivecallbackfilteriterator.getchildren) - Return the inner iterator's children contained in a RecursiveCallbackFilterIterator * [RecursiveCallbackFilteriterator::hasChildren()](recursivecallbackfilteriterator.haschildren) - Check whether the inner iterator's current element has children php EventBufferEvent::setCallbacks EventBufferEvent::setCallbacks ============================== (PECL event >= 1.2.6-beta) EventBufferEvent::setCallbacks — Assigns read, write and event(status) callbacks ### Description ``` public EventBufferEvent::setCallbacks( callable $readcb , callable $writecb , callable $eventcb , mixed $arg = ? ): void ``` Assigns read, write and event(status) callbacks. ### Parameters `readcb` Read event callback. See [About buffer event callbacks](https://www.php.net/manual/en/eventbufferevent.about.callbacks.php) . `writecb` Write event callback. See [About buffer event callbacks](https://www.php.net/manual/en/eventbufferevent.about.callbacks.php) . `eventcb` Status-change event callback. See [About buffer event callbacks](https://www.php.net/manual/en/eventbufferevent.about.callbacks.php) . `arg` A variable that will be passed to all the callbacks. ### Return Values No value is returned. ### See Also * [EventBufferEvent::\_\_construct()](eventbufferevent.construct) - Constructs EventBufferEvent object php The SNMPException class The SNMPException class ======================= Introduction ------------ (PHP 5 >= 5.4.0, PHP 7, PHP 8) Represents an error raised by SNMP. You should not throw a **SNMPException** from your own code. See [Exceptions](language.exceptions) for more information about Exceptions in PHP. Class synopsis -------------- class **SNMPException** extends [RuntimeException](class.runtimeexception) { /\* Properties \*/ protected string [$code](class.snmpexception#snmpexception.props.code); /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } Properties ---------- code `SNMP`library error code. Use [Exception::getCode()](exception.getcode) to access it. php EmptyIterator::next EmptyIterator::next =================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) EmptyIterator::next — The next() method ### Description ``` public EmptyIterator::next(): void ``` No operation, nothing to do. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php IntlCalendar::getDayOfWeekType IntlCalendar::getDayOfWeekType ============================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlCalendar::getDayOfWeekType — Tell whether a day is a weekday, weekend or a day that has a transition between the two ### Description Object-oriented style ``` public IntlCalendar::getDayOfWeekType(int $dayOfWeek): int|false ``` Procedural style ``` intlcal_get_day_of_week_type(IntlCalendar $calendar, int $dayOfWeek): int|false ``` Returns whether the passed day is a weekday (**`IntlCalendar::DOW_TYPE_WEEKDAY`**), a weekend day (**`IntlCalendar::DOW_TYPE_WEEKEND`**), a day during which a transition occurs into the weekend (**`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`**) or a day during which the weekend ceases (**`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`**). If the return is either **`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`** or **`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`**, then [IntlCalendar::getWeekendTransition()](intlcalendar.getweekendtransition) can be called to obtain the time of the transition. This function requires ICU 4.4 or later. ### Parameters `calendar` An [IntlCalendar](class.intlcalendar) instance. `dayOfWeek` One of the constants **`IntlCalendar::DOW_SUNDAY`**, **`IntlCalendar::DOW_MONDAY`**, …, **`IntlCalendar::DOW_SATURDAY`**. ### Return Values Returns one of the constants **`IntlCalendar::DOW_TYPE_WEEKDAY`**, **`IntlCalendar::DOW_TYPE_WEEKEND`**, **`IntlCalendar::DOW_TYPE_WEEKEND_OFFSET`** or **`IntlCalendar::DOW_TYPE_WEEKEND_CEASE`** or **`false`** on failure. ### Examples **Example #1 **IntlCalendar::getDayOfWeekType()**** ``` <?php foreach (array('en_US', 'ar_SA') as $locale) {     echo "Locale: ", Locale::getDisplayName($locale, "en_US"), "\n";     $cal = IntlCalendar::createInstance('UTC', $locale);     for ($i = IntlCalendar::DOW_SUNDAY; $i <= IntlCalendar::DOW_SATURDAY; $i++) {         $type = $cal->getDayOfWeekType($i);         $transition = ($type !== IntlCalendar::DOW_TYPE_WEEKDAY)             ? $cal->getWeekendTransition($i)             : '';         echo $i, " ", $type, " ", $transition, "\n";     }     echo "\n"; } ?> ``` The above example will output: ``` Locale: English (United States) 1 1 86400000 2 0 3 0 4 0 5 0 6 0 7 1 0 Locale: Arabic (Saudi Arabia) 1 0 2 0 3 0 4 0 5 0 6 1 0 7 1 86400000 ``` php None String Operators ---------------- There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('`.=`'), which appends the argument on the right side to the argument on the left side. Please read [Assignment Operators](language.operators.assignment) for more information. ``` <?php $a = "Hello "; $b = $a . "World!"; // now $b contains "Hello World!" $a = "Hello "; $a .= "World!";     // now $a contains "Hello World!" ?> ``` ### See Also * [String type](language.types.string) * [String functions](https://www.php.net/manual/en/ref.strings.php) php IteratorIterator::getInnerIterator IteratorIterator::getInnerIterator ================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) IteratorIterator::getInnerIterator — Get the inner iterator ### Description ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` Get the inner iterator. ### Parameters This function has no parameters. ### Return Values The inner iterator as passed to [IteratorIterator::\_\_construct()](iteratoriterator.construct), or **`null`** when there is no inner iterator. ### See Also * [Iterator](class.iterator) * [OuterIterator](class.outeriterator) php The SolrQuery class The SolrQuery class =================== Introduction ------------ (PECL solr >= 0.9.2) Represents a collection of name-value pairs sent to the Solr server during a request. Class synopsis -------------- class **SolrQuery** extends [SolrModifiableParams](class.solrmodifiableparams) implements [Serializable](class.serializable) { /\* Constants \*/ const int [ORDER\_ASC](class.solrquery#solrquery.constants.order-asc) = 0; const int [ORDER\_DESC](class.solrquery#solrquery.constants.order-desc) = 1; const int [FACET\_SORT\_INDEX](class.solrquery#solrquery.constants.facet-sort-index) = 0; const int [FACET\_SORT\_COUNT](class.solrquery#solrquery.constants.facet-sort-count) = 1; const int [TERMS\_SORT\_INDEX](class.solrquery#solrquery.constants.terms-sort-index) = 0; const int [TERMS\_SORT\_COUNT](class.solrquery#solrquery.constants.terms-sort-count) = 1; /\* Properties \*/ /\* Methods \*/ public [\_\_construct](solrquery.construct)(string `$q` = ?) ``` public addExpandFilterQuery(string $fq): SolrQuery ``` ``` public addExpandSortField(string $field, string $order = ?): SolrQuery ``` ``` public addFacetDateField(string $dateField): SolrQuery ``` ``` public addFacetDateOther(string $value, string $field_override = ?): SolrQuery ``` ``` public addFacetField(string $field): SolrQuery ``` ``` public addFacetQuery(string $facetQuery): SolrQuery ``` ``` public addField(string $field): SolrQuery ``` ``` public addFilterQuery(string $fq): SolrQuery ``` ``` public addGroupField(string $value): SolrQuery ``` ``` public addGroupFunction(string $value): SolrQuery ``` ``` public addGroupQuery(string $value): SolrQuery ``` ``` public addGroupSortField(string $field, int $order = ?): SolrQuery ``` ``` public addHighlightField(string $field): SolrQuery ``` ``` public addMltField(string $field): SolrQuery ``` ``` public addMltQueryField(string $field, float $boost): SolrQuery ``` ``` public addSortField(string $field, int $order = SolrQuery::ORDER_DESC): SolrQuery ``` ``` public addStatsFacet(string $field): SolrQuery ``` ``` public addStatsField(string $field): SolrQuery ``` ``` public collapse(SolrCollapseFunction $collapseFunction): SolrQuery ``` ``` public getExpand(): bool ``` ``` public getExpandFilterQueries(): array ``` ``` public getExpandQuery(): array ``` ``` public getExpandRows(): int ``` ``` public getExpandSortFields(): array ``` ``` public getFacet(): bool ``` ``` public getFacetDateEnd(string $field_override = ?): string ``` ``` public getFacetDateFields(): array ``` ``` public getFacetDateGap(string $field_override = ?): string ``` ``` public getFacetDateHardEnd(string $field_override = ?): string ``` ``` public getFacetDateOther(string $field_override = ?): array ``` ``` public getFacetDateStart(string $field_override = ?): string ``` ``` public getFacetFields(): array ``` ``` public getFacetLimit(string $field_override = ?): int ``` ``` public getFacetMethod(string $field_override = ?): string ``` ``` public getFacetMinCount(string $field_override = ?): int ``` ``` public getFacetMissing(string $field_override = ?): bool ``` ``` public getFacetOffset(string $field_override = ?): int ``` ``` public getFacetPrefix(string $field_override = ?): string ``` ``` public getFacetQueries(): array ``` ``` public getFacetSort(string $field_override = ?): int ``` ``` public getFields(): array ``` ``` public getFilterQueries(): array ``` ``` public getGroup(): bool ``` ``` public getGroupCachePercent(): int ``` ``` public getGroupFacet(): bool ``` ``` public getGroupFields(): array ``` ``` public getGroupFormat(): string ``` ``` public getGroupFunctions(): array ``` ``` public getGroupLimit(): int ``` ``` public getGroupMain(): bool ``` ``` public getGroupNGroups(): bool ``` ``` public getGroupOffset(): int ``` ``` public getGroupQueries(): array ``` ``` public getGroupSortFields(): array ``` ``` public getGroupTruncate(): bool ``` ``` public getHighlight(): bool ``` ``` public getHighlightAlternateField(string $field_override = ?): string ``` ``` public getHighlightFields(): array ``` ``` public getHighlightFormatter(string $field_override = ?): string ``` ``` public getHighlightFragmenter(string $field_override = ?): string ``` ``` public getHighlightFragsize(string $field_override = ?): int ``` ``` public getHighlightHighlightMultiTerm(): bool ``` ``` public getHighlightMaxAlternateFieldLength(string $field_override = ?): int ``` ``` public getHighlightMaxAnalyzedChars(): int ``` ``` public getHighlightMergeContiguous(string $field_override = ?): bool ``` ``` public getHighlightRegexMaxAnalyzedChars(): int ``` ``` public getHighlightRegexPattern(): string ``` ``` public getHighlightRegexSlop(): float ``` ``` public getHighlightRequireFieldMatch(): bool ``` ``` public getHighlightSimplePost(string $field_override = ?): string ``` ``` public getHighlightSimplePre(string $field_override = ?): string ``` ``` public getHighlightSnippets(string $field_override = ?): int ``` ``` public getHighlightUsePhraseHighlighter(): bool ``` ``` public getMlt(): bool ``` ``` public getMltBoost(): bool ``` ``` public getMltCount(): int ``` ``` public getMltFields(): array ``` ``` public getMltMaxNumQueryTerms(): int ``` ``` public getMltMaxNumTokens(): int ``` ``` public getMltMaxWordLength(): int ``` ``` public getMltMinDocFrequency(): int ``` ``` public getMltMinTermFrequency(): int ``` ``` public getMltMinWordLength(): int ``` ``` public getMltQueryFields(): array ``` ``` public getQuery(): string ``` ``` public getRows(): int ``` ``` public getSortFields(): array ``` ``` public getStart(): int ``` ``` public getStats(): bool ``` ``` public getStatsFacets(): array ``` ``` public getStatsFields(): array ``` ``` public getTerms(): bool ``` ``` public getTermsField(): string ``` ``` public getTermsIncludeLowerBound(): bool ``` ``` public getTermsIncludeUpperBound(): bool ``` ``` public getTermsLimit(): int ``` ``` public getTermsLowerBound(): string ``` ``` public getTermsMaxCount(): int ``` ``` public getTermsMinCount(): int ``` ``` public getTermsPrefix(): string ``` ``` public getTermsReturnRaw(): bool ``` ``` public getTermsSort(): int ``` ``` public getTermsUpperBound(): string ``` ``` public getTimeAllowed(): int ``` ``` public removeExpandFilterQuery(string $fq): SolrQuery ``` ``` public removeExpandSortField(string $field): SolrQuery ``` ``` public removeFacetDateField(string $field): SolrQuery ``` ``` public removeFacetDateOther(string $value, string $field_override = ?): SolrQuery ``` ``` public removeFacetField(string $field): SolrQuery ``` ``` public removeFacetQuery(string $value): SolrQuery ``` ``` public removeField(string $field): SolrQuery ``` ``` public removeFilterQuery(string $fq): SolrQuery ``` ``` public removeHighlightField(string $field): SolrQuery ``` ``` public removeMltField(string $field): SolrQuery ``` ``` public removeMltQueryField(string $queryField): SolrQuery ``` ``` public removeSortField(string $field): SolrQuery ``` ``` public removeStatsFacet(string $value): SolrQuery ``` ``` public removeStatsField(string $field): SolrQuery ``` ``` public setEchoHandler(bool $flag): SolrQuery ``` ``` public setEchoParams(string $type): SolrQuery ``` ``` public setExpand(bool $value): SolrQuery ``` ``` public setExpandQuery(string $q): SolrQuery ``` ``` public setExpandRows(int $value): SolrQuery ``` ``` public setExplainOther(string $query): SolrQuery ``` ``` public setFacet(bool $flag): SolrQuery ``` ``` public setFacetDateEnd(string $value, string $field_override = ?): SolrQuery ``` ``` public setFacetDateGap(string $value, string $field_override = ?): SolrQuery ``` ``` public setFacetDateHardEnd(bool $value, string $field_override = ?): SolrQuery ``` ``` public setFacetDateStart(string $value, string $field_override = ?): SolrQuery ``` ``` public setFacetEnumCacheMinDefaultFrequency(int $frequency, string $field_override = ?): SolrQuery ``` ``` public setFacetLimit(int $limit, string $field_override = ?): SolrQuery ``` ``` public setFacetMethod(string $method, string $field_override = ?): SolrQuery ``` ``` public setFacetMinCount(int $mincount, string $field_override = ?): SolrQuery ``` ``` public setFacetMissing(bool $flag, string $field_override = ?): SolrQuery ``` ``` public setFacetOffset(int $offset, string $field_override = ?): SolrQuery ``` ``` public setFacetPrefix(string $prefix, string $field_override = ?): SolrQuery ``` ``` public setFacetSort(int $facetSort, string $field_override = ?): SolrQuery ``` ``` public setGroup(bool $value): SolrQuery ``` ``` public setGroupCachePercent(int $percent): SolrQuery ``` ``` public setGroupFacet(bool $value): SolrQuery ``` ``` public setGroupFormat(string $value): SolrQuery ``` ``` public setGroupLimit(int $value): SolrQuery ``` ``` public setGroupMain(string $value): SolrQuery ``` ``` public setGroupNGroups(bool $value): SolrQuery ``` ``` public setGroupOffset(int $value): SolrQuery ``` ``` public setGroupTruncate(bool $value): SolrQuery ``` ``` public setHighlight(bool $flag): SolrQuery ``` ``` public setHighlightAlternateField(string $field, string $field_override = ?): SolrQuery ``` ``` public setHighlightFormatter(string $formatter, string $field_override = ?): SolrQuery ``` ``` public setHighlightFragmenter(string $fragmenter, string $field_override = ?): SolrQuery ``` ``` public setHighlightFragsize(int $size, string $field_override = ?): SolrQuery ``` ``` public setHighlightHighlightMultiTerm(bool $flag): SolrQuery ``` ``` public setHighlightMaxAlternateFieldLength(int $fieldLength, string $field_override = ?): SolrQuery ``` ``` public setHighlightMaxAnalyzedChars(int $value): SolrQuery ``` ``` public setHighlightMergeContiguous(bool $flag, string $field_override = ?): SolrQuery ``` ``` public setHighlightRegexMaxAnalyzedChars(int $maxAnalyzedChars): SolrQuery ``` ``` public setHighlightRegexPattern(string $value): SolrQuery ``` ``` public setHighlightRegexSlop(float $factor): SolrQuery ``` ``` public setHighlightRequireFieldMatch(bool $flag): SolrQuery ``` ``` public setHighlightSimplePost(string $simplePost, string $field_override = ?): SolrQuery ``` ``` public setHighlightSimplePre(string $simplePre, string $field_override = ?): SolrQuery ``` ``` public setHighlightSnippets(int $value, string $field_override = ?): SolrQuery ``` ``` public setHighlightUsePhraseHighlighter(bool $flag): SolrQuery ``` ``` public setMlt(bool $flag): SolrQuery ``` ``` public setMltBoost(bool $flag): SolrQuery ``` ``` public setMltCount(int $count): SolrQuery ``` ``` public setMltMaxNumQueryTerms(int $value): SolrQuery ``` ``` public setMltMaxNumTokens(int $value): SolrQuery ``` ``` public setMltMaxWordLength(int $maxWordLength): SolrQuery ``` ``` public setMltMinDocFrequency(int $minDocFrequency): SolrQuery ``` ``` public setMltMinTermFrequency(int $minTermFrequency): SolrQuery ``` ``` public setMltMinWordLength(int $minWordLength): SolrQuery ``` ``` public setOmitHeader(bool $flag): SolrQuery ``` ``` public setQuery(string $query): SolrQuery ``` ``` public setRows(int $rows): SolrQuery ``` ``` public setShowDebugInfo(bool $flag): SolrQuery ``` ``` public setStart(int $start): SolrQuery ``` ``` public setStats(bool $flag): SolrQuery ``` ``` public setTerms(bool $flag): SolrQuery ``` ``` public setTermsField(string $fieldname): SolrQuery ``` ``` public setTermsIncludeLowerBound(bool $flag): SolrQuery ``` ``` public setTermsIncludeUpperBound(bool $flag): SolrQuery ``` ``` public setTermsLimit(int $limit): SolrQuery ``` ``` public setTermsLowerBound(string $lowerBound): SolrQuery ``` ``` public setTermsMaxCount(int $frequency): SolrQuery ``` ``` public setTermsMinCount(int $frequency): SolrQuery ``` ``` public setTermsPrefix(string $prefix): SolrQuery ``` ``` public setTermsReturnRaw(bool $flag): SolrQuery ``` ``` public setTermsSort(int $sortType): SolrQuery ``` ``` public setTermsUpperBound(string $upperBound): SolrQuery ``` ``` public setTimeAllowed(int $timeAllowed): SolrQuery ``` public [\_\_destruct](solrquery.destruct)() /\* Inherited methods \*/ public [SolrModifiableParams::\_\_construct](solrmodifiableparams.construct)() public [SolrModifiableParams::\_\_destruct](solrmodifiableparams.destruct)() } Predefined Constants -------------------- **`SolrQuery::ORDER_ASC`** Used to specify that the sorting should be in acending order **`SolrQuery::ORDER_DESC`** Used to specify that the sorting should be in descending order **`SolrQuery::FACET_SORT_INDEX`** Used to specify that the facet should sort by index **`SolrQuery::FACET_SORT_COUNT`** Used to specify that the facet should sort by count **`SolrQuery::TERMS_SORT_INDEX`** Used in the TermsComponent **`SolrQuery::TERMS_SORT_COUNT`** Used in the TermsComponent Table of Contents ----------------- * [SolrQuery::addExpandFilterQuery](solrquery.addexpandfilterquery) — Overrides main filter query, determines which documents to include in the main group * [SolrQuery::addExpandSortField](solrquery.addexpandsortfield) — Orders the documents within the expanded groups (expand.sort parameter) * [SolrQuery::addFacetDateField](solrquery.addfacetdatefield) — Maps to facet.date * [SolrQuery::addFacetDateOther](solrquery.addfacetdateother) — Adds another facet.date.other parameter * [SolrQuery::addFacetField](solrquery.addfacetfield) — Adds another field to the facet * [SolrQuery::addFacetQuery](solrquery.addfacetquery) — Adds a facet query * [SolrQuery::addField](solrquery.addfield) — Specifies which fields to return in the result * [SolrQuery::addFilterQuery](solrquery.addfilterquery) — Specifies a filter query * [SolrQuery::addGroupField](solrquery.addgroupfield) — Add a field to be used to group results * [SolrQuery::addGroupFunction](solrquery.addgroupfunction) — Allows grouping results based on the unique values of a function query (group.func parameter) * [SolrQuery::addGroupQuery](solrquery.addgroupquery) — Allows grouping of documents that match the given query * [SolrQuery::addGroupSortField](solrquery.addgroupsortfield) — Add a group sort field (group.sort parameter) * [SolrQuery::addHighlightField](solrquery.addhighlightfield) — Maps to hl.fl * [SolrQuery::addMltField](solrquery.addmltfield) — Sets a field to use for similarity * [SolrQuery::addMltQueryField](solrquery.addmltqueryfield) — Maps to mlt.qf * [SolrQuery::addSortField](solrquery.addsortfield) — Used to control how the results should be sorted * [SolrQuery::addStatsFacet](solrquery.addstatsfacet) — Requests a return of sub results for values within the given facet * [SolrQuery::addStatsField](solrquery.addstatsfield) — Maps to stats.field parameter * [SolrQuery::collapse](solrquery.collapse) — Collapses the result set to a single document per group * [SolrQuery::\_\_construct](solrquery.construct) — Constructor * [SolrQuery::\_\_destruct](solrquery.destruct) — Destructor * [SolrQuery::getExpand](solrquery.getexpand) — Returns true if group expanding is enabled * [SolrQuery::getExpandFilterQueries](solrquery.getexpandfilterqueries) — Returns the expand filter queries * [SolrQuery::getExpandQuery](solrquery.getexpandquery) — Returns the expand query expand.q parameter * [SolrQuery::getExpandRows](solrquery.getexpandrows) — Returns The number of rows to display in each group (expand.rows) * [SolrQuery::getExpandSortFields](solrquery.getexpandsortfields) — Returns an array of fields * [SolrQuery::getFacet](solrquery.getfacet) — Returns the value of the facet parameter * [SolrQuery::getFacetDateEnd](solrquery.getfacetdateend) — Returns the value for the facet.date.end parameter * [SolrQuery::getFacetDateFields](solrquery.getfacetdatefields) — Returns all the facet.date fields * [SolrQuery::getFacetDateGap](solrquery.getfacetdategap) — Returns the value of the facet.date.gap parameter * [SolrQuery::getFacetDateHardEnd](solrquery.getfacetdatehardend) — Returns the value of the facet.date.hardend parameter * [SolrQuery::getFacetDateOther](solrquery.getfacetdateother) — Returns the value for the facet.date.other parameter * [SolrQuery::getFacetDateStart](solrquery.getfacetdatestart) — Returns the lower bound for the first date range for all date faceting on this field * [SolrQuery::getFacetFields](solrquery.getfacetfields) — Returns all the facet fields * [SolrQuery::getFacetLimit](solrquery.getfacetlimit) — Returns the maximum number of constraint counts that should be returned for the facet fields * [SolrQuery::getFacetMethod](solrquery.getfacetmethod) — Returns the value of the facet.method parameter * [SolrQuery::getFacetMinCount](solrquery.getfacetmincount) — Returns the minimum counts for facet fields should be included in the response * [SolrQuery::getFacetMissing](solrquery.getfacetmissing) — Returns the current state of the facet.missing parameter * [SolrQuery::getFacetOffset](solrquery.getfacetoffset) — Returns an offset into the list of constraints to be used for pagination * [SolrQuery::getFacetPrefix](solrquery.getfacetprefix) — Returns the facet prefix * [SolrQuery::getFacetQueries](solrquery.getfacetqueries) — Returns all the facet queries * [SolrQuery::getFacetSort](solrquery.getfacetsort) — Returns the facet sort type * [SolrQuery::getFields](solrquery.getfields) — Returns the list of fields that will be returned in the response * [SolrQuery::getFilterQueries](solrquery.getfilterqueries) — Returns an array of filter queries * [SolrQuery::getGroup](solrquery.getgroup) — Returns true if grouping is enabled * [SolrQuery::getGroupCachePercent](solrquery.getgroupcachepercent) — Returns group cache percent value * [SolrQuery::getGroupFacet](solrquery.getgroupfacet) — Returns the group.facet parameter value * [SolrQuery::getGroupFields](solrquery.getgroupfields) — Returns group fields (group.field parameter values) * [SolrQuery::getGroupFormat](solrquery.getgroupformat) — Returns the group.format value * [SolrQuery::getGroupFunctions](solrquery.getgroupfunctions) — Returns group functions (group.func parameter values) * [SolrQuery::getGroupLimit](solrquery.getgrouplimit) — Returns the group.limit value * [SolrQuery::getGroupMain](solrquery.getgroupmain) — Returns the group.main value * [SolrQuery::getGroupNGroups](solrquery.getgroupngroups) — Returns the group.ngroups value * [SolrQuery::getGroupOffset](solrquery.getgroupoffset) — Returns the group.offset value * [SolrQuery::getGroupQueries](solrquery.getgroupqueries) — Returns all the group.query parameter values * [SolrQuery::getGroupSortFields](solrquery.getgroupsortfields) — Returns the group.sort value * [SolrQuery::getGroupTruncate](solrquery.getgrouptruncate) — Returns the group.truncate value * [SolrQuery::getHighlight](solrquery.gethighlight) — Returns the state of the hl parameter * [SolrQuery::getHighlightAlternateField](solrquery.gethighlightalternatefield) — Returns the highlight field to use as backup or default * [SolrQuery::getHighlightFields](solrquery.gethighlightfields) — Returns all the fields that Solr should generate highlighted snippets for * [SolrQuery::getHighlightFormatter](solrquery.gethighlightformatter) — Returns the formatter for the highlighted output * [SolrQuery::getHighlightFragmenter](solrquery.gethighlightfragmenter) — Returns the text snippet generator for highlighted text * [SolrQuery::getHighlightFragsize](solrquery.gethighlightfragsize) — Returns the number of characters of fragments to consider for highlighting * [SolrQuery::getHighlightHighlightMultiTerm](solrquery.gethighlighthighlightmultiterm) — Returns whether or not to enable highlighting for range/wildcard/fuzzy/prefix queries * [SolrQuery::getHighlightMaxAlternateFieldLength](solrquery.gethighlightmaxalternatefieldlength) — Returns the maximum number of characters of the field to return * [SolrQuery::getHighlightMaxAnalyzedChars](solrquery.gethighlightmaxanalyzedchars) — Returns the maximum number of characters into a document to look for suitable snippets * [SolrQuery::getHighlightMergeContiguous](solrquery.gethighlightmergecontiguous) — Returns whether or not the collapse contiguous fragments into a single fragment * [SolrQuery::getHighlightRegexMaxAnalyzedChars](solrquery.gethighlightregexmaxanalyzedchars) — Returns the maximum number of characters from a field when using the regex fragmenter * [SolrQuery::getHighlightRegexPattern](solrquery.gethighlightregexpattern) — Returns the regular expression for fragmenting * [SolrQuery::getHighlightRegexSlop](solrquery.gethighlightregexslop) — Returns the deviation factor from the ideal fragment size * [SolrQuery::getHighlightRequireFieldMatch](solrquery.gethighlightrequirefieldmatch) — Returns if a field will only be highlighted if the query matched in this particular field * [SolrQuery::getHighlightSimplePost](solrquery.gethighlightsimplepost) — Returns the text which appears after a highlighted term * [SolrQuery::getHighlightSimplePre](solrquery.gethighlightsimplepre) — Returns the text which appears before a highlighted term * [SolrQuery::getHighlightSnippets](solrquery.gethighlightsnippets) — Returns the maximum number of highlighted snippets to generate per field * [SolrQuery::getHighlightUsePhraseHighlighter](solrquery.gethighlightusephrasehighlighter) — Returns the state of the hl.usePhraseHighlighter parameter * [SolrQuery::getMlt](solrquery.getmlt) — Returns whether or not MoreLikeThis results should be enabled * [SolrQuery::getMltBoost](solrquery.getmltboost) — Returns whether or not the query will be boosted by the interesting term relevance * [SolrQuery::getMltCount](solrquery.getmltcount) — Returns the number of similar documents to return for each result * [SolrQuery::getMltFields](solrquery.getmltfields) — Returns all the fields to use for similarity * [SolrQuery::getMltMaxNumQueryTerms](solrquery.getmltmaxnumqueryterms) — Returns the maximum number of query terms that will be included in any generated query * [SolrQuery::getMltMaxNumTokens](solrquery.getmltmaxnumtokens) — Returns the maximum number of tokens to parse in each document field that is not stored with TermVector support * [SolrQuery::getMltMaxWordLength](solrquery.getmltmaxwordlength) — Returns the maximum word length above which words will be ignored * [SolrQuery::getMltMinDocFrequency](solrquery.getmltmindocfrequency) — Returns the treshold frequency at which words will be ignored which do not occur in at least this many docs * [SolrQuery::getMltMinTermFrequency](solrquery.getmltmintermfrequency) — Returns the frequency below which terms will be ignored in the source document * [SolrQuery::getMltMinWordLength](solrquery.getmltminwordlength) — Returns the minimum word length below which words will be ignored * [SolrQuery::getMltQueryFields](solrquery.getmltqueryfields) — Returns the query fields and their boosts * [SolrQuery::getQuery](solrquery.getquery) — Returns the main query * [SolrQuery::getRows](solrquery.getrows) — Returns the maximum number of documents * [SolrQuery::getSortFields](solrquery.getsortfields) — Returns all the sort fields * [SolrQuery::getStart](solrquery.getstart) — Returns the offset in the complete result set * [SolrQuery::getStats](solrquery.getstats) — Returns whether or not stats is enabled * [SolrQuery::getStatsFacets](solrquery.getstatsfacets) — Returns all the stats facets that were set * [SolrQuery::getStatsFields](solrquery.getstatsfields) — Returns all the statistics fields * [SolrQuery::getTerms](solrquery.getterms) — Returns whether or not the TermsComponent is enabled * [SolrQuery::getTermsField](solrquery.gettermsfield) — Returns the field from which the terms are retrieved * [SolrQuery::getTermsIncludeLowerBound](solrquery.gettermsincludelowerbound) — Returns whether or not to include the lower bound in the result set * [SolrQuery::getTermsIncludeUpperBound](solrquery.gettermsincludeupperbound) — Returns whether or not to include the upper bound term in the result set * [SolrQuery::getTermsLimit](solrquery.gettermslimit) — Returns the maximum number of terms Solr should return * [SolrQuery::getTermsLowerBound](solrquery.gettermslowerbound) — Returns the term to start at * [SolrQuery::getTermsMaxCount](solrquery.gettermsmaxcount) — Returns the maximum document frequency * [SolrQuery::getTermsMinCount](solrquery.gettermsmincount) — Returns the minimum document frequency to return in order to be included * [SolrQuery::getTermsPrefix](solrquery.gettermsprefix) — Returns the term prefix * [SolrQuery::getTermsReturnRaw](solrquery.gettermsreturnraw) — Whether or not to return raw characters * [SolrQuery::getTermsSort](solrquery.gettermssort) — Returns an integer indicating how terms are sorted * [SolrQuery::getTermsUpperBound](solrquery.gettermsupperbound) — Returns the term to stop at * [SolrQuery::getTimeAllowed](solrquery.gettimeallowed) — Returns the time in milliseconds allowed for the query to finish * [SolrQuery::removeExpandFilterQuery](solrquery.removeexpandfilterquery) — Removes an expand filter query * [SolrQuery::removeExpandSortField](solrquery.removeexpandsortfield) — Removes an expand sort field from the expand.sort parameter * [SolrQuery::removeFacetDateField](solrquery.removefacetdatefield) — Removes one of the facet date fields * [SolrQuery::removeFacetDateOther](solrquery.removefacetdateother) — Removes one of the facet.date.other parameters * [SolrQuery::removeFacetField](solrquery.removefacetfield) — Removes one of the facet.date parameters * [SolrQuery::removeFacetQuery](solrquery.removefacetquery) — Removes one of the facet.query parameters * [SolrQuery::removeField](solrquery.removefield) — Removes a field from the list of fields * [SolrQuery::removeFilterQuery](solrquery.removefilterquery) — Removes a filter query * [SolrQuery::removeHighlightField](solrquery.removehighlightfield) — Removes one of the fields used for highlighting * [SolrQuery::removeMltField](solrquery.removemltfield) — Removes one of the moreLikeThis fields * [SolrQuery::removeMltQueryField](solrquery.removemltqueryfield) — Removes one of the moreLikeThis query fields * [SolrQuery::removeSortField](solrquery.removesortfield) — Removes one of the sort fields * [SolrQuery::removeStatsFacet](solrquery.removestatsfacet) — Removes one of the stats.facet parameters * [SolrQuery::removeStatsField](solrquery.removestatsfield) — Removes one of the stats.field parameters * [SolrQuery::setEchoHandler](solrquery.setechohandler) — Toggles the echoHandler parameter * [SolrQuery::setEchoParams](solrquery.setechoparams) — Determines what kind of parameters to include in the response * [SolrQuery::setExpand](solrquery.setexpand) — Enables/Disables the Expand Component * [SolrQuery::setExpandQuery](solrquery.setexpandquery) — Sets the expand.q parameter * [SolrQuery::setExpandRows](solrquery.setexpandrows) — Sets the number of rows to display in each group (expand.rows). Server Default 5 * [SolrQuery::setExplainOther](solrquery.setexplainother) — Sets the explainOther common query parameter * [SolrQuery::setFacet](solrquery.setfacet) — Maps to the facet parameter. Enables or disables facetting * [SolrQuery::setFacetDateEnd](solrquery.setfacetdateend) — Maps to facet.date.end * [SolrQuery::setFacetDateGap](solrquery.setfacetdategap) — Maps to facet.date.gap * [SolrQuery::setFacetDateHardEnd](solrquery.setfacetdatehardend) — Maps to facet.date.hardend * [SolrQuery::setFacetDateStart](solrquery.setfacetdatestart) — Maps to facet.date.start * [SolrQuery::setFacetEnumCacheMinDefaultFrequency](solrquery.setfacetenumcachemindefaultfrequency) — Sets the minimum document frequency used for determining term count * [SolrQuery::setFacetLimit](solrquery.setfacetlimit) — Maps to facet.limit * [SolrQuery::setFacetMethod](solrquery.setfacetmethod) — Specifies the type of algorithm to use when faceting a field * [SolrQuery::setFacetMinCount](solrquery.setfacetmincount) — Maps to facet.mincount * [SolrQuery::setFacetMissing](solrquery.setfacetmissing) — Maps to facet.missing * [SolrQuery::setFacetOffset](solrquery.setfacetoffset) — Sets the offset into the list of constraints to allow for pagination * [SolrQuery::setFacetPrefix](solrquery.setfacetprefix) — Specifies a string prefix with which to limits the terms on which to facet * [SolrQuery::setFacetSort](solrquery.setfacetsort) — Determines the ordering of the facet field constraints * [SolrQuery::setGroup](solrquery.setgroup) — Enable/Disable result grouping (group parameter) * [SolrQuery::setGroupCachePercent](solrquery.setgroupcachepercent) — Enables caching for result grouping * [SolrQuery::setGroupFacet](solrquery.setgroupfacet) — Sets group.facet parameter * [SolrQuery::setGroupFormat](solrquery.setgroupformat) — Sets the group format, result structure (group.format parameter) * [SolrQuery::setGroupLimit](solrquery.setgrouplimit) — Specifies the number of results to return for each group. The server default value is 1 * [SolrQuery::setGroupMain](solrquery.setgroupmain) — If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple * [SolrQuery::setGroupNGroups](solrquery.setgroupngroups) — If true, Solr includes the number of groups that have matched the query in the results * [SolrQuery::setGroupOffset](solrquery.setgroupoffset) — Sets the group.offset parameter * [SolrQuery::setGroupTruncate](solrquery.setgrouptruncate) — If true, facet counts are based on the most relevant document of each group matching the query * [SolrQuery::setHighlight](solrquery.sethighlight) — Enables or disables highlighting * [SolrQuery::setHighlightAlternateField](solrquery.sethighlightalternatefield) — Specifies the backup field to use * [SolrQuery::setHighlightFormatter](solrquery.sethighlightformatter) — Specify a formatter for the highlight output * [SolrQuery::setHighlightFragmenter](solrquery.sethighlightfragmenter) — Sets a text snippet generator for highlighted text * [SolrQuery::setHighlightFragsize](solrquery.sethighlightfragsize) — The size of fragments to consider for highlighting * [SolrQuery::setHighlightHighlightMultiTerm](solrquery.sethighlighthighlightmultiterm) — Use SpanScorer to highlight phrase terms * [SolrQuery::setHighlightMaxAlternateFieldLength](solrquery.sethighlightmaxalternatefieldlength) — Sets the maximum number of characters of the field to return * [SolrQuery::setHighlightMaxAnalyzedChars](solrquery.sethighlightmaxanalyzedchars) — Specifies the number of characters into a document to look for suitable snippets * [SolrQuery::setHighlightMergeContiguous](solrquery.sethighlightmergecontiguous) — Whether or not to collapse contiguous fragments into a single fragment * [SolrQuery::setHighlightRegexMaxAnalyzedChars](solrquery.sethighlightregexmaxanalyzedchars) — Specify the maximum number of characters to analyze * [SolrQuery::setHighlightRegexPattern](solrquery.sethighlightregexpattern) — Specify the regular expression for fragmenting * [SolrQuery::setHighlightRegexSlop](solrquery.sethighlightregexslop) — Sets the factor by which the regex fragmenter can stray from the ideal fragment size * [SolrQuery::setHighlightRequireFieldMatch](solrquery.sethighlightrequirefieldmatch) — Require field matching during highlighting * [SolrQuery::setHighlightSimplePost](solrquery.sethighlightsimplepost) — Sets the text which appears after a highlighted term * [SolrQuery::setHighlightSimplePre](solrquery.sethighlightsimplepre) — Sets the text which appears before a highlighted term * [SolrQuery::setHighlightSnippets](solrquery.sethighlightsnippets) — Sets the maximum number of highlighted snippets to generate per field * [SolrQuery::setHighlightUsePhraseHighlighter](solrquery.sethighlightusephrasehighlighter) — Whether to highlight phrase terms only when they appear within the query phrase * [SolrQuery::setMlt](solrquery.setmlt) — Enables or disables moreLikeThis * [SolrQuery::setMltBoost](solrquery.setmltboost) — Set if the query will be boosted by the interesting term relevance * [SolrQuery::setMltCount](solrquery.setmltcount) — Set the number of similar documents to return for each result * [SolrQuery::setMltMaxNumQueryTerms](solrquery.setmltmaxnumqueryterms) — Sets the maximum number of query terms included * [SolrQuery::setMltMaxNumTokens](solrquery.setmltmaxnumtokens) — Specifies the maximum number of tokens to parse * [SolrQuery::setMltMaxWordLength](solrquery.setmltmaxwordlength) — Sets the maximum word length * [SolrQuery::setMltMinDocFrequency](solrquery.setmltmindocfrequency) — Sets the mltMinDoc frequency * [SolrQuery::setMltMinTermFrequency](solrquery.setmltmintermfrequency) — Sets the frequency below which terms will be ignored in the source docs * [SolrQuery::setMltMinWordLength](solrquery.setmltminwordlength) — Sets the minimum word length * [SolrQuery::setOmitHeader](solrquery.setomitheader) — Exclude the header from the returned results * [SolrQuery::setQuery](solrquery.setquery) — Sets the search query * [SolrQuery::setRows](solrquery.setrows) — Specifies the maximum number of rows to return in the result * [SolrQuery::setShowDebugInfo](solrquery.setshowdebuginfo) — Flag to show debug information * [SolrQuery::setStart](solrquery.setstart) — Specifies the number of rows to skip * [SolrQuery::setStats](solrquery.setstats) — Enables or disables the Stats component * [SolrQuery::setTerms](solrquery.setterms) — Enables or disables the TermsComponent * [SolrQuery::setTermsField](solrquery.settermsfield) — Sets the name of the field to get the Terms from * [SolrQuery::setTermsIncludeLowerBound](solrquery.settermsincludelowerbound) — Include the lower bound term in the result set * [SolrQuery::setTermsIncludeUpperBound](solrquery.settermsincludeupperbound) — Include the upper bound term in the result set * [SolrQuery::setTermsLimit](solrquery.settermslimit) — Sets the maximum number of terms to return * [SolrQuery::setTermsLowerBound](solrquery.settermslowerbound) — Specifies the Term to start from * [SolrQuery::setTermsMaxCount](solrquery.settermsmaxcount) — Sets the maximum document frequency * [SolrQuery::setTermsMinCount](solrquery.settermsmincount) — Sets the minimum document frequency * [SolrQuery::setTermsPrefix](solrquery.settermsprefix) — Restrict matches to terms that start with the prefix * [SolrQuery::setTermsReturnRaw](solrquery.settermsreturnraw) — Return the raw characters of the indexed term * [SolrQuery::setTermsSort](solrquery.settermssort) — Specifies how to sort the returned terms * [SolrQuery::setTermsUpperBound](solrquery.settermsupperbound) — Sets the term to stop at * [SolrQuery::setTimeAllowed](solrquery.settimeallowed) — The time allowed for search to finish
programming_docs
php EvPeriodic::__construct EvPeriodic::\_\_construct ========================= (PECL ev >= 0.2.0) EvPeriodic::\_\_construct — Constructs EvPeriodic watcher object ### Description public **EvPeriodic::\_\_construct**( float `$offset` , string `$interval` , [callable](language.types.callable) `$reschedule_cb` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = **`null`** , int `$priority` = 0 ) Constructs EvPeriodic watcher object and starts it automatically. [EvPeriodic::createStopped()](evperiodic.createstopped) method creates stopped periodic watcher. ### Parameters `offset` See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `interval` See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `reschedule_cb` Reschedule callback. You can pass **`null`**. See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Examples **Example #1 Periodic timer. Use reschedule callback** ``` <?php // Tick each 10.5 seconds function reschedule_cb ($watcher, $now) {  return $now + (10.5. - fmod($now, 10.5)); } $w = new EvPeriodic(0., 0., "reschedule_cb", function ($w, $revents) {  echo time(), PHP_EOL; }); Ev::run(); ?> ``` **Example #2 Periodic timer. Tick every 10.5 seconds starting at now** ``` <?php // Tick every 10.5 seconds starting at now $w = new EvPeriodic(fmod(Ev::now(), 10.5), 10.5, NULL, function ($w, $revents) {  echo time(), PHP_EOL; }); Ev::run(); ?> ``` **Example #3 Hourly watcher** ``` <?php $hourly = EvPeriodic(0, 3600, NULL, function () {  echo "once per hour\n"; }); ?> ``` ### See Also * [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) * [EvTimer](class.evtimer) * [EvPeriodic::createStopped()](evperiodic.createstopped) - Create a stopped EvPeriodic watcher php ReflectionProperty::getType ReflectionProperty::getType =========================== (PHP 7 >= 7.4.0, PHP 8) ReflectionProperty::getType — Gets a property's type ### Description ``` public ReflectionProperty::getType(): ?ReflectionType ``` Gets the associated type of a property. ### Parameters This function has no parameters. ### Return Values Returns a [ReflectionType](class.reflectiontype) if the property has a type, and **`null`** otherwise. ### Examples **Example #1 **ReflectionProperty::getType()** example** ``` <?php class User {     public string $name; } $rp = new ReflectionProperty('User', 'name'); echo $rp->getType()->getName(); ?> ``` The above example will output: ``` string ``` ### See Also * [ReflectionProperty::hasType()](reflectionproperty.hastype) - Checks if property has a type * [ReflectionProperty::isInitialized()](reflectionproperty.isinitialized) - Checks whether a property is initialized php The GearmanTask class The GearmanTask class ===================== Introduction ------------ (PECL gearman >= 0.5.0) Class synopsis -------------- class **GearmanTask** { /\* Methods \*/ ``` public __construct() ``` ``` public create(): GearmanTask|false ``` ``` public data(): string ``` ``` public dataSize(): int ``` ``` public function(): string ``` ``` public functionName(): string ``` ``` public isKnown(): bool ``` ``` public isRunning(): bool ``` ``` public jobHandle(): string ``` ``` public recvData(int $data_len): array ``` ``` public returnCode(): int ``` ``` public sendData(string $data): int ``` ``` public sendWorkload(string $data): int ``` ``` public taskDenominator(): int ``` ``` public taskNumerator(): int ``` ``` public unique(): string ``` ``` public uuid(): string ``` } Table of Contents ----------------- * [GearmanTask::\_\_construct](gearmantask.construct) — Create a GearmanTask instance * [GearmanTask::create](gearmantask.create) — Create a task (deprecated) * [GearmanTask::data](gearmantask.data) — Get data returned for a task * [GearmanTask::dataSize](gearmantask.datasize) — Get the size of returned data * [GearmanTask::function](gearmantask.function) — Get associated function name (deprecated) * [GearmanTask::functionName](gearmantask.functionname) — Get associated function name * [GearmanTask::isKnown](gearmantask.isknown) — Determine if task is known * [GearmanTask::isRunning](gearmantask.isrunning) — Test whether the task is currently running * [GearmanTask::jobHandle](gearmantask.jobhandle) — Get the job handle * [GearmanTask::recvData](gearmantask.recvdata) — Read work or result data into a buffer for a task * [GearmanTask::returnCode](gearmantask.returncode) — Get the last return code * [GearmanTask::sendData](gearmantask.senddata) — Send data for a task (deprecated) * [GearmanTask::sendWorkload](gearmantask.sendworkload) — Send data for a task * [GearmanTask::taskDenominator](gearmantask.taskdenominator) — Get completion percentage denominator * [GearmanTask::taskNumerator](gearmantask.tasknumerator) — Get completion percentage numerator * [GearmanTask::unique](gearmantask.unique) — Get the unique identifier for a task * [GearmanTask::uuid](gearmantask.uuid) — Get the unique identifier for a task (deprecated) php SolrQuery::setGroupCachePercent SolrQuery::setGroupCachePercent =============================== (PECL solr >= 2.2.0) SolrQuery::setGroupCachePercent — Enables caching for result grouping ### Description ``` public SolrQuery::setGroupCachePercent(int $percent): SolrQuery ``` Setting this parameter to a number greater than 0 enables caching for result grouping. Result Grouping executes two searches; this option caches the second search. The server default value is 0. Testing has shown that group caching only improves search time with Boolean, wildcard, and fuzzy queries. For simple queries like term or "match all" queries, group caching degrades performance. group.cache.percent parameter ### Parameters `percent` ### Return Values ### Errors/Exceptions Emits [SolrIllegalArgumentException](class.solrillegalargumentexception) in case of an invalid parameter was passed. ### See Also * [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter) * [SolrQuery::addGroupField()](solrquery.addgroupfield) - Add a field to be used to group results * [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter) * [SolrQuery::addGroupQuery()](solrquery.addgroupquery) - Allows grouping of documents that match the given query * [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter) * [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter * [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter * [SolrQuery::setGroupLimit()](solrquery.setgrouplimit) - Specifies the number of results to return for each group. The server default value is 1 * [SolrQuery::setGroupMain()](solrquery.setgroupmain) - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple * [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results * [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query * [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter) php The CachingIterator class The CachingIterator class ========================= Introduction ------------ (PHP 5, PHP 7, PHP 8) This object supports cached iteration over another iterator. Class synopsis -------------- class **CachingIterator** extends [IteratorIterator](class.iteratoriterator) implements [ArrayAccess](class.arrayaccess), [Countable](class.countable), [Stringable](class.stringable) { /\* Constants \*/ public const int [CALL\_TOSTRING](class.cachingiterator#cachingiterator.constants.call-tostring); public const int [CATCH\_GET\_CHILD](class.cachingiterator#cachingiterator.constants.catch-get-child); public const int [TOSTRING\_USE\_KEY](class.cachingiterator#cachingiterator.constants.tostring-use-key); public const int [TOSTRING\_USE\_CURRENT](class.cachingiterator#cachingiterator.constants.tostring-use-current); public const int [TOSTRING\_USE\_INNER](class.cachingiterator#cachingiterator.constants.tostring-use-inner); public const int [FULL\_CACHE](class.cachingiterator#cachingiterator.constants.full-cache); /\* Methods \*/ public [\_\_construct](cachingiterator.construct)([Iterator](class.iterator) `$iterator`, int `$flags` = CachingIterator::CALL\_TOSTRING) ``` public count(): int ``` ``` public current(): mixed ``` ``` public getCache(): array ``` ``` public getFlags(): int ``` ``` public getInnerIterator(): Iterator ``` ``` public hasNext(): bool ``` ``` public key(): scalar ``` ``` public next(): void ``` ``` public offsetExists(string $key): bool ``` ``` public offsetGet(string $key): mixed ``` ``` public offsetSet(string $key, mixed $value): void ``` ``` public offsetUnset(string $key): void ``` ``` public rewind(): void ``` ``` public setFlags(int $flags): void ``` ``` public __toString(): string ``` ``` public valid(): bool ``` /\* Inherited methods \*/ ``` public IteratorIterator::current(): mixed ``` ``` public IteratorIterator::getInnerIterator(): ?Iterator ``` ``` public IteratorIterator::key(): mixed ``` ``` public IteratorIterator::next(): void ``` ``` public IteratorIterator::rewind(): void ``` ``` public IteratorIterator::valid(): bool ``` } Predefined Constants -------------------- **`CachingIterator::CALL_TOSTRING`** Convert every element to string. **`CachingIterator::CATCH_GET_CHILD`** Don't throw exception in accessing children. **`CachingIterator::TOSTRING_USE_KEY`** Use [key](cachingiterator.key) for conversion to string. **`CachingIterator::TOSTRING_USE_CURRENT`** Use [current](cachingiterator.current) for conversion to string. **`CachingIterator::TOSTRING_USE_INNER`** Use [inner](cachingiterator.getinneriterator) for conversion to string. **`CachingIterator::FULL_CACHE`** Cache all read data. Changelog --------- | Version | Description | | --- | --- | | 8.0.0 | **CachingIterator** implements [Stringable](class.stringable) now. | Table of Contents ----------------- * [CachingIterator::\_\_construct](cachingiterator.construct) — Construct a new CachingIterator object for the iterator * [CachingIterator::count](cachingiterator.count) — The number of elements in the iterator * [CachingIterator::current](cachingiterator.current) — Return the current element * [CachingIterator::getCache](cachingiterator.getcache) — Retrieve the contents of the cache * [CachingIterator::getFlags](cachingiterator.getflags) — Get flags used * [CachingIterator::getInnerIterator](cachingiterator.getinneriterator) — Returns the inner iterator * [CachingIterator::hasNext](cachingiterator.hasnext) — Check whether the inner iterator has a valid next element * [CachingIterator::key](cachingiterator.key) — Return the key for the current element * [CachingIterator::next](cachingiterator.next) — Move the iterator forward * [CachingIterator::offsetExists](cachingiterator.offsetexists) — The offsetExists purpose * [CachingIterator::offsetGet](cachingiterator.offsetget) — The offsetGet purpose * [CachingIterator::offsetSet](cachingiterator.offsetset) — The offsetSet purpose * [CachingIterator::offsetUnset](cachingiterator.offsetunset) — The offsetUnset purpose * [CachingIterator::rewind](cachingiterator.rewind) — Rewind the iterator * [CachingIterator::setFlags](cachingiterator.setflags) — The setFlags purpose * [CachingIterator::\_\_toString](cachingiterator.tostring) — Return the string representation of the current element * [CachingIterator::valid](cachingiterator.valid) — Check whether the current element is valid php DOMText::isElementContentWhitespace DOMText::isElementContentWhitespace =================================== (No version information available, might only be in Git) DOMText::isElementContentWhitespace — Returns whether this text node contains whitespace in element content ### Description ``` public DOMText::isElementContentWhitespace(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. php filter_input_array filter\_input\_array ==================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) filter\_input\_array — Gets external variables and optionally filters them ### Description ``` filter_input_array(int $type, array|int $options = FILTER_DEFAULT, bool $add_empty = true): array|false|null ``` This function is useful for retrieving many values without repetitively calling [filter\_input()](function.filter-input). ### Parameters `type` One of **`INPUT_GET`**, **`INPUT_POST`**, **`INPUT_COOKIE`**, **`INPUT_SERVER`**, or **`INPUT_ENV`**. `options` An array defining the arguments. A valid key is a string containing a variable name and a valid value is either a [filter type](https://www.php.net/manual/en/filter.filters.php), or an array optionally specifying the filter, flags and options. If the value is an array, valid keys are `filter` which specifies the [filter type](https://www.php.net/manual/en/filter.filters.php), `flags` which specifies any flags that apply to the filter, and `options` which specifies any options that apply to the filter. See the example below for a better understanding. This parameter can be also an integer holding a [filter constant](https://www.php.net/manual/en/filter.constants.php). Then all values in the input array are filtered by this filter. `add_empty` Add missing keys as **`null`** to the return value. ### Return Values An array containing the values of the requested variables on success. If the input array designated by `type` is not populated, the function returns **`null`** if the **`FILTER_NULL_ON_FAILURE`** flag is not given, or **`false`** otherwise. For other failures, **`false`** is returned. An array value will be **`false`** if the filter fails, or **`null`** if the variable is not set. Or if the flag **`FILTER_NULL_ON_FAILURE`** is used, it returns **`false`** if the variable is not set and **`null`** if the filter fails. If the `add_empty` parameter is **`false`**, no array element will be added for unset variables. ### Examples **Example #1 A **filter\_input\_array()** example** ``` <?php /* data actually came from POST $_POST = array(     'product_id' => 'libgd<script>',     'component'  => array('10'),     'version'    => '2.0.33',     'testarray'  => array('2', '23', '10', '12'),     'testscalar' => '2', ); */ $args = array(     'product_id'   => FILTER_SANITIZE_ENCODED,     'component'    => array('filter'    => FILTER_VALIDATE_INT,                             'flags'     => FILTER_REQUIRE_ARRAY,                              'options'   => array('min_range' => 1, 'max_range' => 10)                            ),     'version'      => FILTER_SANITIZE_ENCODED,     'doesnotexist' => FILTER_VALIDATE_INT,     'testscalar'   => array(                             'filter' => FILTER_VALIDATE_INT,                             'flags'  => FILTER_REQUIRE_SCALAR,                            ),     'testarray'    => array(                             'filter' => FILTER_VALIDATE_INT,                             'flags'  => FILTER_REQUIRE_ARRAY,                            ) ); $myinputs = filter_input_array(INPUT_POST, $args); var_dump($myinputs); echo "\n"; ?> ``` The above example will output: ``` array(6) { ["product_id"]=> string(17) "libgd%3Cscript%3E" ["component"]=> array(1) { [0]=> int(10) } ["version"]=> string(6) "2.0.33" ["doesnotexist"]=> NULL ["testscalar"]=> int(2) ["testarray"]=> array(4) { [0]=> int(2) [1]=> int(23) [2]=> int(10) [3]=> int(12) } } ``` ### Notes > > **Note**: > > > There is no `REQUEST_TIME` key in **`INPUT_SERVER`** array because it is inserted into the [$\_SERVER](reserved.variables.server) later. > > ### See Also * [filter\_input()](function.filter-input) - Gets a specific external variable by name and optionally filters it * [filter\_var\_array()](function.filter-var-array) - Gets multiple variables and optionally filters them * [Types of filters](https://www.php.net/manual/en/filter.filters.php) php SolrClient::ping SolrClient::ping ================ (PECL solr >= 0.9.2) SolrClient::ping — Checks if Solr server is still up ### Description ``` public SolrClient::ping(): SolrPingResponse ``` Checks if the Solr server is still alive. Sends a HEAD request to the Apache Solr server. ### Parameters This function has no parameters. ### Return Values Returns a [SolrPingResponse](class.solrpingresponse) object on success and throws an exception on failure. ### Errors/Exceptions Throws [SolrClientException](class.solrclientexception) if the client had failed, or there was a connection issue. Throws [SolrServerException](class.solrserverexception) if the Solr Server had failed to satisfy the request. ### Examples **Example #1 **SolrClient::ping()** example** ``` <?php $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT, ); $client = new SolrClient($options); $pingresponse = $client->ping(); ?> ``` The above example will output something similar to: php RecursiveTreeIterator::rewind RecursiveTreeIterator::rewind ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::rewind — Rewind iterator ### Description ``` public RecursiveTreeIterator::rewind(): void ``` Rewinds the iterator to the first element of the top level inner iterator. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php SolrQuery::setGroupLimit SolrQuery::setGroupLimit ======================== (PECL solr >= 2.2.0) SolrQuery::setGroupLimit — Specifies the number of results to return for each group. The server default value is 1 ### Description ``` public SolrQuery::setGroupLimit(int $value): SolrQuery ``` Specifies the number of results to return for each group. The server default value is 1. ### Parameters `value` ### Return Values ### See Also * [SolrQuery::setGroup()](solrquery.setgroup) - Enable/Disable result grouping (group parameter) * [SolrQuery::addGroupField()](solrquery.addgroupfield) - Add a field to be used to group results * [SolrQuery::addGroupFunction()](solrquery.addgroupfunction) - Allows grouping results based on the unique values of a function query (group.func parameter) * [SolrQuery::addGroupQuery()](solrquery.addgroupquery) - Allows grouping of documents that match the given query * [SolrQuery::addGroupSortField()](solrquery.addgroupsortfield) - Add a group sort field (group.sort parameter) * [SolrQuery::setGroupFacet()](solrquery.setgroupfacet) - Sets group.facet parameter * [SolrQuery::setGroupOffset()](solrquery.setgroupoffset) - Sets the group.offset parameter * [SolrQuery::setGroupMain()](solrquery.setgroupmain) - If true, the result of the first field grouping command is used as the main result list in the response, using group.format=simple * [SolrQuery::setGroupNGroups()](solrquery.setgroupngroups) - If true, Solr includes the number of groups that have matched the query in the results * [SolrQuery::setGroupTruncate()](solrquery.setgrouptruncate) - If true, facet counts are based on the most relevant document of each group matching the query * [SolrQuery::setGroupFormat()](solrquery.setgroupformat) - Sets the group format, result structure (group.format parameter) * [SolrQuery::setGroupCachePercent()](solrquery.setgroupcachepercent) - Enables caching for result grouping
programming_docs
php SQLite3Result::__construct SQLite3Result::\_\_construct ============================ (No version information available, might only be in Git) SQLite3Result::\_\_construct — Constructs an SQLite3Result ### Description private **SQLite3Result::\_\_construct**() [SQLite3Result](class.sqlite3result) instances are created by [SQLite3::query()](sqlite3.query) and [SQLite3Stmt::execute()](sqlite3stmt.execute). ### Parameters This function has no parameters. php FilterIterator::getInnerIterator FilterIterator::getInnerIterator ================================ (PHP 5 >= 5.1.0, PHP 7, PHP 8) FilterIterator::getInnerIterator — Get the inner iterator ### Description ``` public FilterIterator::getInnerIterator(): Iterator ``` **Warning**This function is currently not documented; only its argument list is available. Get the inner iterator. ### Parameters This function has no parameters. ### Return Values The inner iterator. php DOMNode::C14NFile DOMNode::C14NFile ================= (PHP 5 >= 5.2.0, PHP 7, PHP 8) DOMNode::C14NFile — Canonicalize nodes to a file ### Description ``` public DOMNode::C14NFile( string $uri, bool $exclusive = false, bool $withComments = false, ?array $xpath = null, ?array $nsPrefixes = null ): int|false ``` Canonicalize nodes to a file. ### Parameters `uri` Path to write the output to. `exclusive` Enable exclusive parsing of only the nodes matched by the provided xpath or namespace prefixes. `withComments` Retain comments in output. `xpath` An array of `xpath`s to filter the nodes by. `nsPrefixes` An array of namespace prefixes to filter the nodes by. ### Return Values Number of bytes written or **`false`** on failure ### See Also * [DOMNode::C14N()](domnode.c14n) - Canonicalize nodes to a string php Ds\Stack::peek Ds\Stack::peek ============== (PECL ds >= 1.0.0) Ds\Stack::peek — Returns the value at the top of the stack ### Description ``` public Ds\Stack::peek(): mixed ``` Returns the value at the top of the stack, but does not remove it. ### Parameters This function has no parameters. ### Return Values The value at the top of the stack. ### Errors/Exceptions [UnderflowException](class.underflowexception) if empty. ### Examples **Example #1 **Ds\Stack::peek()** example** ``` <?php $stack = new \Ds\Stack(); $stack->push("a"); $stack->push("b"); $stack->push("c"); var_dump($stack->peek()); ?> ``` The above example will output something similar to: ``` string(1) "c" ``` php OAuth::getRequestToken OAuth::getRequestToken ====================== (PECL OAuth >= 0.99.1) OAuth::getRequestToken — Fetch a request token ### Description ``` public OAuth::getRequestToken(string $request_token_url, string $callback_url = ?, string $http_method = ?): array ``` Fetch a request token, secret and any additional response parameters from the service provider. ### Parameters `request_token_url` URL to the request token API. `callback_url` OAuth callback URL. If `callback_url` is passed and is an empty value, it is set to "oob" to address the OAuth 2009.1 advisory. `http_method` HTTP method to use, e.g. `GET` or `POST`. ### Return Values Returns an array containing the parsed OAuth response on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | PECL oauth 1.0.0 | Previously returned **`null`** on failure, instead of **`false`**. | | PECL oauth 0.99.9 | The `callback_url` parameter was added | ### Examples **Example #1 **OAuth::getRequestToken()** example** ``` <?php try {     $oauth = new OAuth(OAUTH_CONSUMER_KEY,OAUTH_CONSUMER_SECRET);     $request_token_info = $oauth->getRequestToken("https://example.com/oauth/request_token");     if(!empty($request_token_info)) {         print_r($request_token_info);     } else {         print "Failed fetching request token, response was: " . $oauth->getLastResponse();     } } catch(OAuthException $E) {     echo "Response: ". $E->lastResponse . "\n"; } ?> ``` The above example will output something similar to: ``` Array ( [oauth_token] => some_token [oauth_token_secret] => some_token_secret ) ``` ### See Also * [OAuth::getLastResponse()](oauth.getlastresponse) - Get the last response * [OAuth::getLastResponseInfo()](oauth.getlastresponseinfo) - Get HTTP information about the last response php Ds\Queue::__construct Ds\Queue::\_\_construct ======================= (PECL ds >= 1.0.0) Ds\Queue::\_\_construct — Creates a new instance ### Description public **Ds\Queue::\_\_construct**([mixed](language.types.declarations#language.types.declarations.mixed) `$values` = ?) Creates a new instance, using either a [traversable](class.traversable) object or an array for the initial `values`. ### Parameters `values` A traversable object or an array to use for the initial values. ### Examples **Example #1 **Ds\Queue::\_\_construct()** example** ``` <?php $queue = new \Ds\Queue(); var_dump($queue); $queue = new \Ds\Queue([1, 2, 3]); var_dump($queue); ?> ``` The above example will output something similar to: ``` object(Ds\Queue)#2 (0) { } object(Ds\Queue)#2 (3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ``` php MessageFormatter::getErrorCode MessageFormatter::getErrorCode ============================== msgfmt\_get\_error\_code ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) MessageFormatter::getErrorCode -- msgfmt\_get\_error\_code — Get the error code from last operation ### Description Object-oriented style ``` public MessageFormatter::getErrorCode(): int ``` Procedural style ``` msgfmt_get_error_code(MessageFormatter $formatter): int ``` Get the error code from last operation. ### Parameters `formatter` The message formatter ### Return Values The error code, one of UErrorCode values. Initial value is U\_ZERO\_ERROR. ### See Also * [msgfmt\_get\_error\_message()](messageformatter.geterrormessage) - Get the error text from the last operation * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure php The Hashable interface The Hashable interface ====================== Introduction ------------ (No version information available, might only be in Git) Hashable is an interface which allows objects to be used as keys. It’s an alternative to [spl\_object\_hash()](function.spl-object-hash), which determines an object’s hash based on its handle: this means that two objects that are considered equal by an implicit definition would not treated as equal because they are not the same instance. [hash()](function.hash) is used to return a scalar value to be used as the object's hash value, which determines where it goes in the hash table. While this value does not have to be unique, objects which are equal must have the same hash value. **equals()** is used to determine if two objects are equal. It's guaranteed that the comparing object will be an instance of the same class as the subject. Interface synopsis ------------------ class **Ds\Hashable** { /\* Methods \*/ ``` abstract public equals(object $obj): bool ``` ``` abstract public hash(): mixed ``` } Table of Contents ----------------- * [Ds\Hashable::equals](ds-hashable.equals) — Determines whether an object is equal to the current instance * [Ds\Hashable::hash](ds-hashable.hash) — Returns a scalar value to be used as a hash value php IntlChar::getBidiPairedBracket IntlChar::getBidiPairedBracket ============================== (PHP 7, PHP 8) IntlChar::getBidiPairedBracket — Get the paired bracket character for a code point ### Description ``` public static IntlChar::getBidiPairedBracket(int|string $codepoint): int|string|null ``` Maps the specified character to its paired bracket character. For `Bidi_Paired_Bracket_Type!=None`, this is the same as [IntlChar::charMirror()](intlchar.charmirror). Otherwise `codepoint` itself is returned. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns the paired bracket code point, or `codepoint` itself if there is no such mapping. Returns **`null`** on failure. The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::getBidiPairedBracket(91)); var_dump(IntlChar::getBidiPairedBracket('[')); ?> ``` The above example will output: ``` int(93) string(1) "]" ``` ### See Also * [IntlChar::charMirror()](intlchar.charmirror) - Get the "mirror-image" character for a code point * **`IntlChar::PROPERTY_BIDI_PAIRED_BRACKET`** * **`IntlChar::PROPERTY_BIDI_PAIRED_BRACKET_TYPE`** php odbc_autocommit odbc\_autocommit ================ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_autocommit — Toggle autocommit behaviour ### Description ``` odbc_autocommit(resource $odbc, bool $enable = false): int|bool ``` Toggles autocommit behaviour. By default, auto-commit is on for a connection. Disabling auto-commit is equivalent with starting a transaction. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `enable` If `enable` is **`true`**, auto-commit is enabled, if it is **`false`** auto-commit is disabled. ### Return Values Without the `enable` parameter, this function returns auto-commit status for `odbc`. Non-zero is returned if auto-commit is on, 0 if it is off, or **`false`** if an error occurs. If `enable` is set, this function returns **`true`** on success and **`false`** on failure. ### See Also * [odbc\_commit()](function.odbc-commit) - Commit an ODBC transaction * [odbc\_rollback()](function.odbc-rollback) - Rollback a transaction php EventBuffer::__construct EventBuffer::\_\_construct ========================== (PECL event >= 1.2.6-beta) EventBuffer::\_\_construct — Constructs EventBuffer object ### Description ``` public EventBuffer::__construct() ``` Constructs EventBuffer object ### Parameters This function has no parameters. ### Return Values Returns EventBuffer object. php ImagickDraw::clone ImagickDraw::clone ================== (PECL imagick 2, PECL imagick 3) ImagickDraw::clone — Makes an exact copy of the specified ImagickDraw object ### Description ``` public ImagickDraw::clone(): ImagickDraw ``` **Warning**This function is currently not documented; only its argument list is available. Makes an exact copy of the specified [ImagickDraw](class.imagickdraw) object. ### Return Values returns an exact copy of the specified [ImagickDraw](class.imagickdraw) object. php tidyNode::isAsp tidyNode::isAsp =============== (PHP 5, PHP 7, PHP 8) tidyNode::isAsp — Checks if this node is ASP ### Description ``` public tidyNode::isAsp(): bool ``` Tells whether the current node is ASP. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the node is ASP, **`false`** otherwise. ### Examples **Example #1 Extract ASP code from a mixed HTML document** ``` <?php $html = <<< HTML <html><head> <?php echo '<title>title</title>'; ?> <#    /* JSTE code */   alert('Hello World');  #> </head> <body> <?php   // PHP code   echo 'hello world!'; ?> <%   /* ASP code */   response.write("Hello World!") %> <!-- Comments --> Hello World </body></html> Outside HTML HTML; $tidy = tidy_parse_string($html); $num = 0; get_nodes($tidy->html()); function get_nodes($node) {     // check if the current node is of requested type     if($node->isAsp()) {         echo "\n\n# asp node #" . ++$GLOBALS['num'] . "\n";         echo $node->value;     }     // check if the current node has childrens     if($node->hasChildren()) {         foreach($node->child as $child) {             get_nodes($child);         }     } } ?> ``` The above example will output: ``` # asp node #1 <% /* ASP code */ response.write("Hello World!") %> ``` php readline_callback_handler_install readline\_callback\_handler\_install ==================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) readline\_callback\_handler\_install — Initializes the readline callback interface and terminal, prints the prompt and returns immediately ### Description ``` readline_callback_handler_install(string $prompt, callable $callback): bool ``` Sets up a readline callback interface then prints `prompt` and immediately returns. Calling this function twice without removing the previous callback interface will automatically and conveniently overwrite the old interface. The callback feature is useful when combined with [stream\_select()](function.stream-select) as it allows interleaving of IO and user input, unlike [readline()](function.readline). ### Parameters `prompt` The prompt message. `callback` The `callback` function takes one parameter; the user input returned. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Readline Callback Interface Example** ``` <?php function rl_callback($ret) {     global $c, $prompting;     echo "You entered: $ret\n";     $c++;     if ($c > 10) {         $prompting = false;         readline_callback_handler_remove();     } else {         readline_callback_handler_install("[$c] Enter something: ", 'rl_callback');     } } $c = 1; $prompting = true; readline_callback_handler_install("[$c] Enter something: ", 'rl_callback'); while ($prompting) {     $w = NULL;     $e = NULL;     $n = stream_select($r = array(STDIN), $w, $e, null);     if ($n && in_array(STDIN, $r)) {         // read a character, will call the callback when a newline is entered         readline_callback_read_char();     } } echo "Prompting disabled. All done.\n"; ?> ``` ### See Also * [readline\_callback\_handler\_remove()](function.readline-callback-handler-remove) - Removes a previously installed callback handler and restores terminal settings * [readline\_callback\_read\_char()](function.readline-callback-read-char) - Reads a character and informs the readline callback interface when a line is received * [stream\_select()](function.stream-select) - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds php ReflectionClass::inNamespace ReflectionClass::inNamespace ============================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionClass::inNamespace — Checks if in namespace ### Description ``` public ReflectionClass::inNamespace(): bool ``` Checks if this class is defined in a namespace. ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ReflectionClass::inNamespace()** example** ``` <?php namespace A\B; class Foo { } $function = new \ReflectionClass('stdClass'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); $function = new \ReflectionClass('A\\B\\Foo'); var_dump($function->inNamespace()); var_dump($function->getName()); var_dump($function->getNamespaceName()); var_dump($function->getShortName()); ?> ``` The above example will output: ``` bool(false) string(8) "stdClass" string(0) "" string(8) "stdClass" bool(true) string(7) "A\B\Foo" string(3) "A\B" string(3) "Foo" ``` ### See Also * [ReflectionClass::getNamespaceName()](reflectionclass.getnamespacename) - Gets namespace name * [PHP Namespaces](https://www.php.net/manual/en/language.namespaces.php) php use_soap_error_handler use\_soap\_error\_handler ========================= (PHP 5, PHP 7, PHP 8) use\_soap\_error\_handler — Set whether to use the SOAP error handler ### Description ``` use_soap_error_handler(bool $enable = true): bool ``` This function sets whether or not to use the SOAP error handler in the SOAP server. It will return the previous value. If set to **`true`**, details of errors in a [SoapServer](class.soapserver) application will be sent to the client as a SOAP fault message. If **`false`**, the standard PHP error handler is used. The default is to send error to the client as SOAP fault message. ### Parameters `enable` Set to **`true`** to send error details to clients. ### Return Values Returns the original value. ### See Also * [set\_error\_handler()](function.set-error-handler) - Sets a user-defined error handler function * [set\_exception\_handler()](function.set-exception-handler) - Sets a user-defined exception handler function php is_nan is\_nan ======= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) is\_nan — Finds whether a value is not a number ### Description ``` is_nan(float $num): bool ``` Checks whether `num` is 'not a number', like the result of `acos(1.01)`. ### Parameters `num` The value to check ### Return Values Returns **`true`** if `num` is 'not a number', else **`false`**. ### Examples **Example #1 **is\_nan()** example** ``` <?php // Invalid calculation, will return a  // NaN value $nan = acos(8); var_dump($nan, is_nan($nan)); ?> ``` The above example will output: ``` float(NAN) bool(true) ``` ### See Also * [is\_finite()](function.is-finite) - Finds whether a value is a legal finite number * [is\_infinite()](function.is-infinite) - Finds whether a value is infinite php SplStack::__construct SplStack::\_\_construct ======================= (PHP 5 >= 5.3.0, PHP 7) SplStack::\_\_construct — Constructs a new stack implemented using a doubly linked list ### Description public **SplStack::\_\_construct**() This constructs a new empty stack. > > **Note**: > > > This method automatically sets the iterator mode to SplDoublyLinkedList::IT\_MODE\_LIFO. > > ### Parameters This function has no parameters. ### Examples **Example #1 **SplStack::\_\_construct()** example** ``` <?php $q = new SplStack(); $q[] = 1; $q[] = 2; $q[] = 3; foreach ($q as $elem)  {  echo $elem."\n"; } ?> ``` The above example will output: ``` 3 2 1 ``` php IntlTimeZone::__construct IntlTimeZone::\_\_construct =========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::\_\_construct — Private constructor to disallow direct instantiation ### Description private **IntlTimeZone::\_\_construct**() ### Parameters This function has no parameters. php fbird_blob_cancel fbird\_blob\_cancel =================== (PHP 5, PHP 7 < 7.4.0) fbird\_blob\_cancel — Cancel creating blob ### Description ``` fbird_blob_cancel(resource $blob_handle): bool ``` This function will discard a BLOB if it has not yet been closed by [fbird\_blob\_close()](function.fbird-blob-close). ### Parameters `blob_handle` A BLOB handle opened with [fbird\_blob\_create()](function.fbird-blob-create). ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [fbird\_blob\_close()](function.fbird-blob-close) - Alias of ibase\_blob\_close * [fbird\_blob\_create()](function.fbird-blob-create) - Alias of ibase\_blob\_create * [fbird\_blob\_import()](function.fbird-blob-import) - Alias of ibase\_blob\_import
programming_docs
php Locale::getPrimaryLanguage Locale::getPrimaryLanguage ========================== locale\_get\_primary\_language ============================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::getPrimaryLanguage -- locale\_get\_primary\_language — Gets the primary language for the input locale ### Description Object-oriented style ``` public static Locale::getPrimaryLanguage(string $locale): ?string ``` Procedural style ``` locale_get_primary_language(string $locale): ?string ``` Gets the primary language for the input locale ### Parameters `locale` The locale to extract the primary language code from ### Return Values The language code associated with the language. Returns **`null`** when the length of `locale` exceeds **`INTL_MAX_LOCALE_LEN`**. ### Examples **Example #1 **locale\_get\_primary\_language()** example** ``` <?php echo locale_get_primary_language('zh-Hant'); ?> ``` **Example #2 OO example** ``` <?php echo Locale::getPrimaryLanguage('zh-Hant'); ?> ``` The above example will output: ``` zh ``` ### See Also * [locale\_get\_script()](locale.getscript) - Gets the script for the input locale * [locale\_get\_region()](locale.getregion) - Gets the region for the input locale * [locale\_get\_all\_variants()](locale.getallvariants) - Gets the variants for the input locale php imap_setflag_full imap\_setflag\_full =================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_setflag\_full — Sets flags on messages ### Description ``` imap_setflag_full( IMAP\Connection $imap, string $sequence, string $flag, int $options = 0 ): bool ``` Causes a store to add the specified `flag` to the flags set for the messages in the specified `sequence`. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `sequence` A sequence of message numbers. You can enumerate desired messages with the `X,Y` syntax, or retrieve all messages within an interval with the `X:Y` syntax `flag` The flags which you can set are `\Seen`, `\Answered`, `\Flagged`, `\Deleted`, and `\Draft` as defined by [» RFC2060](http://www.faqs.org/rfcs/rfc2060). `options` A bit mask that may contain the single option: * **`ST_UID`** - The sequence argument contains UIDs instead of sequence numbers ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **imap\_setflag\_full()** example** ``` <?php $mbox = imap_open("{imap.example.org:143}", "username", "password")      or die("can't connect: " . imap_last_error()); $status = imap_setflag_full($mbox, "2,5", "\\Seen \\Flagged"); echo gettype($status) . "\n"; echo $status . "\n"; imap_close($mbox); ?> ``` ### See Also * [imap\_clearflag\_full()](function.imap-clearflag-full) - Clears flags on messages php RarEntry::__toString RarEntry::\_\_toString ====================== (PECL rar >= 2.0.0) RarEntry::\_\_toString — Get text representation of entry ### Description ``` public RarEntry::__toString(): string ``` **RarEntry::\_\_toString()** returns a textual representation for this entry. It includes whether the entry is a file or a directory (symbolic links and other special objects will be treated as files), the UTF-8 name of the entry and its CRC. The form and content of this representation may be changed in the future, so they cannot be relied upon. ### Parameters This function has no parameters. ### Return Values A textual representation for the entry. php $argv $argv ===== (PHP 4, PHP 5, PHP 7, PHP 8) $argv — Array of arguments passed to script ### Description Contains an array of all the arguments passed to the script when running from the [command line](https://www.php.net/manual/en/features.commandline.php). > **Note**: The first argument $argv[0] is always the name that was used to run the script. > > > **Note**: This variable is not available when [register\_argc\_argv](https://www.php.net/manual/en/ini.core.php#ini.register-argc-argv) is disabled. > > ### Examples **Example #1 $argv example** ``` <?php var_dump($argv); ?> ``` When executing the example with: php script.php arg1 arg2 arg3 The above example will output something similar to: ``` array(4) { [0]=> string(10) "script.php" [1]=> string(4) "arg1" [2]=> string(4) "arg2" [3]=> string(4) "arg3" } ``` ### Notes > > **Note**: > > > This is also available as [$\_SERVER['argv']](reserved.variables.server). > > ### See Also * [getopt()](function.getopt) - Gets options from the command line argument list * [[$argc](reserved.variables.argc)](reserved.variables.argc) php Zookeeper::close Zookeeper::close ================ (PECL zookeeper >= 0.5.0) Zookeeper::close — Close the zookeeper handle and free up any resources ### Description ``` public Zookeeper::close(): void ``` ### Parameters This function has no parameters. ### Return Values No value is returned. ### Errors/Exceptions This method emits [ZookeeperException](class.zookeeperexception) and it's derivatives when closing an uninitialized instance. ### See Also * [Zookeeper::\_\_construct()](zookeeper.construct) - Create a handle to used communicate with zookeeper * [Zookeeper::connect()](zookeeper.connect) - Create a handle to used communicate with zookeeper * [ZookeeperException](class.zookeeperexception) php imap_errors imap\_errors ============ (PHP 4, PHP 5, PHP 7, PHP 8) imap\_errors — Returns all of the IMAP errors that have occurred ### Description ``` imap_errors(): array|false ``` Gets all of the IMAP errors (if any) that have occurred during this page request or since the error stack was reset. When **imap\_errors()** is called, the error stack is subsequently cleared. ### Parameters This function has no parameters. ### Return Values This function returns an array of all of the IMAP error messages generated since the last **imap\_errors()** call, or the beginning of the page. Returns **`false`** if no error messages are available. ### See Also * [imap\_last\_error()](function.imap-last-error) - Gets the last IMAP error that occurred during this page request * [imap\_alerts()](function.imap-alerts) - Returns all IMAP alert messages that have occurred php IntlChar::tolower IntlChar::tolower ================= (PHP 7, PHP 8) IntlChar::tolower — Make Unicode character lowercase ### Description ``` public static IntlChar::tolower(int|string $codepoint): int|string|null ``` The given character is mapped to its lowercase equivalent. If the character has no lowercase equivalent, the original character itself is returned. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns the Simple\_Lowercase\_Mapping of the code point, if any; otherwise the code point itself. Returns **`null`** on failure. The return type is int unless the code point was passed as a UTF-8 string, in which case a string is returned. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::tolower("A")); var_dump(IntlChar::tolower("a")); var_dump(IntlChar::tolower("Φ")); var_dump(IntlChar::tolower("φ")); var_dump(IntlChar::tolower("1")); var_dump(IntlChar::tolower(ord("A"))); var_dump(IntlChar::tolower(ord("a"))); ?> ``` The above example will output: ``` string(1) "a" string(1) "a" string(2) "φ" string(2) "φ" string(1) "1" int(97) int(97) ``` ### See Also * [IntlChar::totitle()](intlchar.totitle) - Make Unicode character titlecase * [IntlChar::toupper()](intlchar.toupper) - Make Unicode character uppercase * [mb\_strtolower()](function.mb-strtolower) - Make a string lowercase php IntlTimeZone::getCanonicalID IntlTimeZone::getCanonicalID ============================ intltz\_get\_canonical\_id ========================== (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::getCanonicalID -- intltz\_get\_canonical\_id — Get the canonical system timezone ID or the normalized custom time zone ID for the given time zone ID ### Description Object-oriented style (method): ``` public static IntlTimeZone::getCanonicalID(string $timezoneId, bool &$isSystemId = null): string|false ``` Procedural style: ``` intltz_get_canonical_id(string $timezoneId, bool &$isSystemId = null): string|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `timezoneId` `isSystemId` ### Return Values php DOMNode::removeChild DOMNode::removeChild ==================== (PHP 5, PHP 7, PHP 8) DOMNode::removeChild — Removes child from list of children ### Description ``` public DOMNode::removeChild(DOMNode $child): DOMNode|false ``` This functions removes a child from a list of children. ### Parameters `child` The removed child. ### Return Values If the child could be removed the function returns the old child. ### Errors/Exceptions **`DOM_NO_MODIFICATION_ALLOWED_ERR`** Raised if this node is readonly. **`DOM_NOT_FOUND`** Raised if `child` is not a child of this node. ### Examples The following example will delete the `chapter` element of our XML document. **Example #1 Removing a child** ``` <?php $doc = new DOMDocument; $doc->load('book.xml'); $book = $doc->documentElement; // we retrieve the chapter and remove it from the book $chapter = $book->getElementsByTagName('chapter')->item(0); $oldchapter = $book->removeChild($chapter); echo $doc->saveXML(); ?> ``` The above example will output: ``` <?xml version="1.0" encoding="utf-8"?> <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"> <book id="listing"> <title>My lists</title> </book> ``` ### See Also * [DOMChildNode::remove()](domchildnode.remove) - Removes the node * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children * [DOMNode::replaceChild()](domnode.replacechild) - Replaces a child php imap_body imap\_body ========== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_body — Read the message body ### Description ``` imap_body(IMAP\Connection $imap, int $message_num, int $flags = 0): string|false ``` **imap\_body()** returns the body of the message, numbered `message_num` in the current mailbox. **imap\_body()** will only return a verbatim copy of the message body. To extract single parts of a multipart MIME-encoded message you have to use [imap\_fetchstructure()](function.imap-fetchstructure) to analyze its structure and [imap\_fetchbody()](function.imap-fetchbody) to extract a copy of a single body component. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `message_num` The message number `flags` The optional `flags` are a bit mask with one or more of the following: * **`FT_UID`** - The `message_num` is a UID * **`FT_PEEK`** - Do not set the \Seen flag if not already set * **`FT_INTERNAL`** - The return string is in internal format, will not canonicalize to CRLF. ### Return Values Returns the body of the specified message, as a string, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | php sodium_crypto_secretstream_xchacha20poly1305_init_pull sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_pull =========================================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_pull — Initialize a secretstream context for decryption ### Description ``` sodium_crypto_secretstream_xchacha20poly1305_init_pull(string $header, string $key): string ``` Initialize a secretstream context for decryption. ### Parameters `header` The header of the secretstream. This should be one of the values produced by [sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_push()](function.sodium-crypto-secretstream-xchacha20poly1305-init-push). `key` Encryption key (256-bit). ### Return Values Secretstream state. ### Examples **Example #1 **sodium\_crypto\_secretstream\_xchacha20poly1305\_init\_pull()** example** ``` <?php function decrypt_file(string $inputFilePath, string $outputFilePath, string $key): void {     $inputFile = fopen($inputFilePath, 'rb');     $outputFile = fopen($outputFilePath, 'wb');     $header = fread($inputFile, 24);     $state = sodium_crypto_secretstream_xchacha20poly1305_init_pull($header, $key);     $inputFileSize = fstat($inputFile)['size'];     // Decrypt the file and write its contents to the output file:     for ($i = 24; $i < $inputFileSize; $i += 8192) {         $ctxt_chunk = fread($inputFile, 8192);         // We're not using $tag, but in real protocols you can use this on encrypt to e.g.         // trigger a re-key or indicate the end of file. Then, on decrypt, you can assert         // this behavior.         [$ptxt_chunk, $tag] = sodium_crypto_secretstream_xchacha20poly1305_pull($state, $ctxt_chunk);         fwrite($outputFile, $ptxt_chunk);     }     sodium_memzero($state);     fclose($inputFile);     fclose($outputFile); } // sodium_crypto_secretstream_xchacha20poly1305_keygen() $key = sodium_base642bin('MS0lzb7HC+thY6jY01pkTE/cwsQxnRq0/2L1eL4Hxn8=', SODIUM_BASE64_VARIANT_ORIGINAL); $example = sodium_hex2bin('971e33b255f0990ef3931caf761c59136efa77b434832f28ec719e3ff73f5aec38b3bba1574ab5b70a8844d8da36a668e802cfea2c'); file_put_contents('hello.enc', $example); decrypt_file('hello.enc', 'hello.txt.decrypted', $key); var_dump(file_get_contents('hello.txt.decrypted')); ?> ``` The above example will output something similar to: ``` string(12) "Hello world!" ``` php Yac::get Yac::get ======== (PECL yac >= 1.0.0) Yac::get — Retrieve values from cache ### Description ``` public Yac::get(string|array $key, int &$cas = null): mixed ``` Retrieve values from cache ### Parameters `key` string keys, or array of multiple keys. `cas` if not **`null`**, it will be set to the retrieved item's cas. ### Return Values mixed on success, false on failure php gmp_and gmp\_and ======== (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) gmp\_and — Bitwise AND ### Description ``` gmp_and(GMP|int|string $num1, GMP|int|string $num2): GMP ``` Calculates bitwise AND of two GMP numbers. ### Parameters `num1` A [GMP](class.gmp) object, an int or a numeric string. `num2` A [GMP](class.gmp) object, an int or a numeric string. ### Return Values A GMP number representing the bitwise `AND` comparison. ### Examples **Example #1 **gmp\_and()** example** ``` <?php $and1 = gmp_and("0xfffffffff4", "0x4"); $and2 = gmp_and("0xfffffffff4", "0x8"); echo gmp_strval($and1) . "\n"; echo gmp_strval($and2) . "\n"; ?> ``` The above example will output: ``` 4 0 ``` php Yaf_Loader::getLocalNamespace Yaf\_Loader::getLocalNamespace ============================== (Yaf >=1.0.0) Yaf\_Loader::getLocalNamespace — Retrive all register namespaces info ### Description ``` public Yaf_Loader::getNamespaces(): array ``` get registered namespaces info ### Parameters This function has no parameters. ### Return Values array php SolrObject::offsetUnset SolrObject::offsetUnset ======================= (PECL solr >= 0.9.2) SolrObject::offsetUnset — Unsets the value for the property ### Description ``` public SolrObject::offsetUnset(string $property_name): void ``` Unsets the value for the property. This is used when the object is treated as an array. This object is read-only. This should never be attempted. ### Parameters `property_name` The name of the property. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **SolrObject::offsetUnset()** example** ``` <?php /* ... */ ?> ``` The above example will output something similar to: ``` ... ``` php ZipArchive::setMtimeIndex ZipArchive::setMtimeIndex ========================= (PHP >= 8.0.0, PECL zip >= 1.16.0) ZipArchive::setMtimeIndex — Set the modification time of an entry defined by its index ### Description ``` public ZipArchive::setMtimeIndex(int $index, int $timestamp, int $flags = 0): bool ``` Set the modification time of an entry defined by its index. ### Parameters `index` Index of the entry. `timestamp` The modification time (unix timestamp) of the file. `flags` Optional flags, unused for now. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples This example creates a ZIP file archive test.zip and add the file test.txt with its modification date. **Example #1 Archive a file** ``` <?php $zip = new ZipArchive(); if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {     $zip->addFile('text.txt');     $zip->setMtimeIndex(0, mktime(0,0,0,12,25,2019));     $zip->close();     echo "Ok\n"; } else {     echo "KO\n"; } ?> ``` ### Notes > > **Note**: > > > This function is only available if built against libzip ≥ 1.0.0. > > ### See Also * [ZipArchive::setMtimeName()](ziparchive.setmtimename) - Set the modification time of an entry defined by its name php pcntl_waitpid pcntl\_waitpid ============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_waitpid — Waits on or returns the status of a forked child ### Description ``` pcntl_waitpid( int $process_id, int &$status, int $flags = 0, array &$resource_usage = [] ): int ``` Suspends execution of the current process until a child as specified by the `process_id` argument has exited, or until a signal is delivered whose action is to terminate the current process or to call a signal handling function. If a child as requested by `process_id` has already exited by the time of the call (a so-called "zombie" process), the function returns immediately. Any system resources used by the child are freed. Please see your system's waitpid(2) man page for specific details as to how waitpid works on your system. ### Parameters `process_id` The value of `process_id` can be one of the following: **possible values for `process_id`**| `< -1` | wait for any child process whose process group ID is equal to the absolute value of `process_id`. | | `-1` | wait for any child process; this is the same behaviour that the wait function exhibits. | | `0` | wait for any child process whose process group ID is equal to that of the calling process. | | `> 0` | wait for the child whose process ID is equal to the value of `process_id`. | > > **Note**: > > > Specifying `-1` as the `process_id` is equivalent to the functionality [pcntl\_wait()](function.pcntl-wait) provides (minus `flags`). > > `status` **pcntl\_waitpid()** will store status information in the `status` parameter which can be evaluated using the following functions: [pcntl\_wifexited()](function.pcntl-wifexited), [pcntl\_wifstopped()](function.pcntl-wifstopped), [pcntl\_wifsignaled()](function.pcntl-wifsignaled), [pcntl\_wexitstatus()](function.pcntl-wexitstatus), [pcntl\_wtermsig()](function.pcntl-wtermsig) and [pcntl\_wstopsig()](function.pcntl-wstopsig). `flags` The value of `flags` is the value of zero or more of the following two global constants `OR`'ed together: **possible values for `flags`**| `WNOHANG` | return immediately if no child has exited. | | `WUNTRACED` | return for children which are stopped, and whose status has not been reported. | ### Return Values **pcntl\_waitpid()** returns the process ID of the child which exited, -1 on error or zero if **`WNOHANG`** was used and no child was available ### See Also * [pcntl\_fork()](function.pcntl-fork) - Forks the currently running process * [pcntl\_signal()](function.pcntl-signal) - Installs a signal handler * [pcntl\_wifexited()](function.pcntl-wifexited) - Checks if status code represents a normal exit * [pcntl\_wifstopped()](function.pcntl-wifstopped) - Checks whether the child process is currently stopped * [pcntl\_wifsignaled()](function.pcntl-wifsignaled) - Checks whether the status code represents a termination due to a signal * [pcntl\_wexitstatus()](function.pcntl-wexitstatus) - Returns the return code of a terminated child * [pcntl\_wtermsig()](function.pcntl-wtermsig) - Returns the signal which caused the child to terminate * [pcntl\_wstopsig()](function.pcntl-wstopsig) - Returns the signal which caused the child to stop
programming_docs
php IntlTimeZone::toDateTimeZone IntlTimeZone::toDateTimeZone ============================ intltz\_to\_date\_time\_zone ============================ (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) IntlTimeZone::toDateTimeZone -- intltz\_to\_date\_time\_zone — Convert to [DateTimeZone](class.datetimezone) object ### Description Object-oriented style (method): ``` public IntlTimeZone::toDateTimeZone(): DateTimeZone|false ``` Procedural style: ``` intltz_to_date_time_zone(IntlTimeZone $timezone): DateTimeZone|false ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php XMLParser::__construct XMLParser::\_\_construct ======================== (PHP 8) XMLParser::\_\_construct — Construct a new XMLParser instance ### Description public **XMLParser::\_\_construct**() Throws an [Error](class.error), since [XMLParser](class.xmlparser) is not constructable directly. Use [xml\_parser\_create()](function.xml-parser-create) or [xml\_parser\_create\_ns()](function.xml-parser-create-ns) instead. ### Parameters This function has no parameters. php eio_fdatasync eio\_fdatasync ============== (PECL eio >= 0.0.1dev) eio\_fdatasync — Synchronize a file's in-core state with storage device ### Description ``` eio_fdatasync( mixed $fd, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_fdatasync()** synchronizes a file's in-core state with storage device. ### Parameters `fd` Stream, Socket resource, or numeric file descriptor, e.g. returned by [eio\_open()](function.eio-open). `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_fdatasync()** returns request resource on success, or **`false`** on failure. php pcntl_rfork pcntl\_rfork ============ (PHP 8 >= 8.1.0) pcntl\_rfork — Manipulates process resources ### Description ``` pcntl_rfork(int $flags, int $signal = 0): int ``` Manipulates process resources. ### Parameters `flags` The `flags` parameter determines which resources of the invoking process (parent) are shared by the new process (child) or initialized to their default values. `flags` is the logical OR of some subset of: * **`RFPROC`**: If set a new process is created; otherwise changes affect the current process. * **`RFNOWAIT`**: If set, the child process will be dissociated from the parent. Upon exit the child will not leave a status for the parent to collect. * **`RFFDG`**: If set, the invoker's file descriptor table is copied; otherwise the two processes share a single table. * **`RFCFDG`**: If set, the new process starts with a clean file descriptor table. Is mutually exclusive with `RFFDG`. * **`RFLINUXTHPN`**: If set, the kernel will return SIGUSR1 instead of SIGCHILD upon thread exit for the child. This is intended to do Linux clone exit parent notification. `signal` The signal number. ### Return Values On success, the PID of the child process is returned in the parent's thread of execution, and a `0` is returned in the child's thread of execution. On failure, a `-1` will be returned in the parent's context, no child process will be created, and a PHP error is raised. ### Examples **Example #1 **pcntl\_rfork()** example** ``` <?php $pid = pcntl_rfork(RFNOWAIT|RFTSIGZMB, SIGUSR1); if ($pid > 0) {   // This is the parent process.   var_dump($pid); } else {   // This is the child process.   var_dump($pid);   sleep(2); // as the child does not wait, so we see its "pid" } ?> ``` The above example will output something similar to: ``` int(77093) int(0) ``` ### See Also * [pcntl\_fork()](function.pcntl-fork) - Forks the currently running process * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child * [pcntl\_signal()](function.pcntl-signal) - Installs a signal handler * [cli\_set\_process\_title()](function.cli-set-process-title) - Sets the process title php SolrQuery::getStats SolrQuery::getStats =================== (PECL solr >= 0.9.2) SolrQuery::getStats — Returns whether or not stats is enabled ### Description ``` public SolrQuery::getStats(): bool ``` Returns whether or not stats is enabled ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php mysqli_stmt::$error mysqli\_stmt::$error ==================== mysqli\_stmt\_error =================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::$error -- mysqli\_stmt\_error — Returns a string description for last statement error ### Description Object-oriented style string [$mysqli\_stmt->error](mysqli-stmt.error); Procedural style ``` mysqli_stmt_error(mysqli_stmt $statement): string ``` Returns a string containing the error message for the most recently invoked statement function that can succeed or fail. ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values A string that describes the error. An empty string if no error occurred. ### Examples **Example #1 Object-oriented style** ``` <?php /* Open a connection */ $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } $mysqli->query("CREATE TABLE myCountry LIKE Country"); $mysqli->query("INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = $mysqli->prepare($query)) {     /* drop table */     $mysqli->query("DROP TABLE myCountry");     /* execute query */     $stmt->execute();     printf("Error: %s.\n", $stmt->error);     /* close statement */     $stmt->close(); } /* close connection */ $mysqli->close(); ?> ``` **Example #2 Procedural style** ``` <?php /* Open a connection */ $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } mysqli_query($link, "CREATE TABLE myCountry LIKE Country"); mysqli_query($link, "INSERT INTO myCountry SELECT * FROM Country"); $query = "SELECT Name, Code FROM myCountry ORDER BY Name"; if ($stmt = mysqli_prepare($link, $query)) {     /* drop table */     mysqli_query($link, "DROP TABLE myCountry");     /* execute query */     mysqli_stmt_execute($stmt);     printf("Error: %s.\n", mysqli_stmt_error($stmt));     /* close statement */     mysqli_stmt_close($stmt); } /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Error: Table 'world.myCountry' doesn't exist. ``` ### See Also * [mysqli\_stmt\_errno()](mysqli-stmt.errno) - Returns the error code for the most recent statement call * [mysqli\_stmt\_sqlstate()](mysqli-stmt.sqlstate) - Returns SQLSTATE error from previous statement operation php uopz_get_return uopz\_get\_return ================= (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_get\_return — Gets a previous set return value for a function ### Description ``` uopz_get_return(string $function): mixed ``` ``` uopz_get_return(string $class, string $function): mixed ``` Gets the return value of the `function` previously set by [uopz\_set\_return()](function.uopz-set-return). ### Parameters `class` The name of the class containing the function `function` The name of the function ### Return Values The return value or Closure previously set. ### Examples **Example #1 **uopz\_get\_return()** example** ``` <?php uopz_set_return("strlen", 42); echo uopz_get_return("strlen"); ?> ``` The above example will output: ``` 42 ``` php ErrorException ErrorException ============== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) An Error Exception. Class synopsis -------------- class **ErrorException** extends [Exception](class.exception) { /\* Properties \*/ protected int [$severity](class.errorexception#errorexception.props.severity) = E\_ERROR; /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/ public [\_\_construct](errorexception.construct)( string `$message` = "", int `$code` = 0, int `$severity` = **`E_ERROR`**, ?string `$filename` = **`null`**, ?int `$line` = **`null`**, ?[Throwable](class.throwable) `$previous` = **`null`** ) ``` final public getSeverity(): int ``` /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } Properties ---------- severity The severity of the exception Examples -------- **Example #1 Use [set\_error\_handler()](function.set-error-handler) to change error messages into ErrorException.** ``` <?php function exception_error_handler($severity, $message, $file, $line) {     if (!(error_reporting() & $severity)) {         // This error code is not included in error_reporting         return;     }     throw new ErrorException($message, 0, $severity, $file, $line); } set_error_handler("exception_error_handler"); /* Trigger exception */ strpos(); ?> ``` The above example will output something similar to: ``` Fatal error: Uncaught exception 'ErrorException' with message 'strpos() expects at least 2 parameters, 0 given' in /home/bjori/tmp/ex.php:12 Stack trace: #0 [internal function]: exception_error_handler(2, 'strpos() expect...', '/home/bjori/php...', 12, Array) #1 /home/bjori/php/cleandocs/test.php(12): strpos() #2 {main} thrown in /home/bjori/tmp/ex.php on line 12 ``` Table of Contents ----------------- * [ErrorException::\_\_construct](errorexception.construct) — Constructs the exception * [ErrorException::getSeverity](errorexception.getseverity) — Gets the exception severity php gethostbyaddr gethostbyaddr ============= (PHP 4, PHP 5, PHP 7, PHP 8) gethostbyaddr — Get the Internet host name corresponding to a given IP address ### Description ``` gethostbyaddr(string $ip): string|false ``` Returns the host name of the Internet host specified by `ip`. ### Parameters `ip` The host IP address. ### Return Values Returns the host name on success, the unmodified `ip` on failure, or **`false`** on malformed input. ### Examples **Example #1 A simple **gethostbyaddr()** example** ``` <?php $hostname = gethostbyaddr($_SERVER['REMOTE_ADDR']); echo $hostname; ?> ``` ### See Also * [gethostbyname()](function.gethostbyname) - Get the IPv4 address corresponding to a given Internet host name * [gethostbynamel()](function.gethostbynamel) - Get a list of IPv4 addresses corresponding to a given Internet host name php Parle\RLexer::dump Parle\RLexer::dump ================== (PECL parle >= 0.5.1) Parle\RLexer::dump — Dump the state machine ### Description ``` public Parle\RLexer::dump(): void ``` Dump the current state machine to stdout. ### Parameters This function has no parameters. ### Return Values No value is returned. php Gmagick::raiseimage Gmagick::raiseimage =================== (PECL gmagick >= Unknown) Gmagick::raiseimage — Creates a simulated 3d button-like effect ### Description ``` public Gmagick::raiseimage( int $width, int $height, int $x, int $y, bool $raise ): Gmagick ``` Creates a simulated three-dimensional button-like effect by lightening and darkening the edges of the image. Members width and height of raise\_info define the width of the vertical and horizontal edge of the effect. ### Parameters `width` Width of the area to raise. `height` Height of the area to raise. `x` X coordinate. `y` Y coordinate. `raise` A value other than zero creates a 3-D raise effect, otherwise it has a lowered effect. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php socket_wsaprotocol_info_export socket\_wsaprotocol\_info\_export ================================= (PHP 7 >= 7.3.0, PHP 8) socket\_wsaprotocol\_info\_export — Exports the WSAPROTOCOL\_INFO Structure ### Description ``` socket_wsaprotocol_info_export(Socket $socket, int $process_id): string|false ``` Exports the `WSAPROTOCOL_INFO` structure into shared memory and returns an identifier to be used with [socket\_wsaprotocol\_info\_import()](function.socket-wsaprotocol-info-import). The exported ID is only valid for the given `process_id`. > **Note**: This function is available only on Windows. > > ### Parameters `socket` A [Socket](class.socket) instance. `process_id` The ID of the process which will import the socket. ### Return Values Returns an identifier to be used for the import, or **`false`** on failure ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `socket` is a [Socket](class.socket) instance now; previously, it was a resource. | ### See Also * [socket\_wsaprotocol\_info\_import()](function.socket-wsaprotocol-info-import) - Imports a Socket from another Process * [socket\_wsaprotocol\_info\_release()](function.socket-wsaprotocol-info-release) - Releases an exported WSAPROTOCOL\_INFO Structure php EvWatcher::getLoop EvWatcher::getLoop ================== (PECL ev >= 0.2.0) EvWatcher::getLoop — Returns the loop responsible for the watcher ### Description ``` public EvWatcher::getLoop(): EvLoop ``` Returns the loop responsible for the watcher ### Parameters This function has no parameters. ### Return Values Returns [EvLoop](class.evloop) event loop object responsible for the watcher. php bcscale bcscale ======= (PHP 4, PHP 5, PHP 7, PHP 8) bcscale — Set or get default scale parameter for all bc math functions ### Description ``` bcscale(int $scale): int ``` Sets the default scale parameter for all subsequent calls to bc math functions that do not explicitly specify a scale parameter. ``` bcscale(null $scale = null): int ``` Gets the current scale factor. ### Parameters `scale` The scale factor. ### Return Values Returns the old scale when used as setter. Otherwise the current scale is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `scale` is now nullable. | | 7.3.0 | **bcscale()** can now be used to get the current scale factor; when used as setter, it now returns the old scale value. Formerly, `scale` was mandatory, and **bcscale()** always returned **`true`**. | ### Examples **Example #1 **bcscale()** example** ``` <?php // default scale : 3 bcscale(3); echo bcdiv('105', '6.55957'); // 16.007 // this is the same without bcscale() echo bcdiv('105', '6.55957', 3); // 16.007 ?> ``` php VarnishAdmin::setCompat VarnishAdmin::setCompat ======================= (PECL varnish >= 0.9.2) VarnishAdmin::setCompat — Set the class compat configuration param ### Description ``` public VarnishAdmin::setCompat(int $compat): void ``` ### Parameters `compat` Varnish compatibility option. ### Return Values php SplFileInfo::openFile SplFileInfo::openFile ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::openFile — Gets an SplFileObject object for the file ### Description ``` public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject ``` Creates an [SplFileObject](class.splfileobject) object of the file. This is useful because [SplFileObject](class.splfileobject) contains additional methods for manipulating the file whereas [SplFileInfo](class.splfileinfo) is only useful for gaining information, like whether the file is writable. ### Parameters `mode` The mode for opening the file. See the [fopen()](function.fopen) documentation for descriptions of possible modes. The default is read only. `useIncludePath` When set to **`true`**, the filename is also searched for within the [include\_path](https://www.php.net/manual/en/ini.core.php#ini.include-path) `context` Refer to the [context](https://www.php.net/manual/en/context.php) section of the manual for a description of `contexts`. ### Return Values The opened file as an [SplFileObject](class.splfileobject) object. ### Errors/Exceptions A [RuntimeException](class.runtimeexception) if the file cannot be opened (e.g. insufficient access rights). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `context` is now nullable. | ### Examples **Example #1 **SplFileInfo::openFile()** example** ``` <?php $fileinfo = new SplFileInfo('/tmp/foo.txt'); if ($fileinfo->isWritable()) {     $fileobj = $fileinfo->openFile('a');     $fileobj->fwrite("appended this sample text"); } ?> ``` ### See Also * [SplFileObject](class.splfileobject) * [stream\_context\_create()](function.stream-context-create) - Creates a stream context * [fopen()](function.fopen) - Opens file or URL php DateTime::createFromFormat DateTime::createFromFormat ========================== date\_create\_from\_format ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) DateTime::createFromFormat -- date\_create\_from\_format — Parses a time string according to a specified format ### Description Object-oriented style ``` public static DateTime::createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false ``` Procedural style ``` date_create_from_format(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false ``` Returns a new DateTime object representing the date and time specified by the `datetime` string, which was formatted in the given `format`. Like [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) and [date\_create\_immutable\_from\_format()](function.date-create-immutable-from-format), respectively, but creates a [DateTime](class.datetime) object. ### Parameters See [DateTimeImmutable::createFromFormat](datetimeimmutable.createfromformat). ### Return Values Returns a new DateTime instance or **`false`** on failure. ### See Also * [DateTimeImmutable::createFromFormat()](datetimeimmutable.createfromformat) - Parses a time string according to a specified format
programming_docs
php Ds\Queue::isEmpty Ds\Queue::isEmpty ================= (PECL ds >= 1.0.0) Ds\Queue::isEmpty — Returns whether the queue is empty ### Description ``` public Ds\Queue::isEmpty(): bool ``` Returns whether the queue is empty. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the queue is empty, **`false`** otherwise. ### Examples **Example #1 **Ds\Queue::isEmpty()** example** ``` <?php $a = new \Ds\Queue([1, 2, 3]); $b = new \Ds\Queue(); var_dump($a->isEmpty()); var_dump($b->isEmpty()); ?> ``` The above example will output something similar to: ``` bool(false) bool(true) ``` php pg_fetch_array pg\_fetch\_array ================ (PHP 4, PHP 5, PHP 7, PHP 8) pg\_fetch\_array — Fetch a row as an array ### Description ``` pg_fetch_array(PgSql\Result $result, ?int $row = null, int $mode = PGSQL_BOTH): array|false ``` **pg\_fetch\_array()** returns an array that corresponds to the fetched row (record). **pg\_fetch\_array()** is an extended version of [pg\_fetch\_row()](function.pg-fetch-row). In addition to storing the data in the numeric indices (field number) to the result array, it can also store the data using associative indices (field name). It stores both indices by default. > **Note**: This function sets NULL fields to the PHP **`null`** value. > > **pg\_fetch\_array()** is NOT significantly slower than using [pg\_fetch\_row()](function.pg-fetch-row), and is significantly easier to use. ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). `row` Row number in result to fetch. Rows are numbered from 0 upwards. If omitted or **`null`**, the next row is fetched. `mode` An optional parameter that controls how the returned array is indexed. `mode` is a constant and can take the following values: **`PGSQL_ASSOC`**, **`PGSQL_NUM`** and **`PGSQL_BOTH`**. Using **`PGSQL_NUM`**, the function will return an array with numerical indices, using **`PGSQL_ASSOC`** it will return only associative indices while **`PGSQL_BOTH`** will return both numerical and associative indices. ### Return Values An array indexed numerically (beginning with 0) or associatively (indexed by field name), or both. Each value in the array is represented as a string. Database `NULL` values are returned as **`null`**. **`false`** is returned if `row` exceeds the number of rows in the set, there are no more rows, or on any other error. Fetching from the result of a query other than SELECT will also return **`false`**. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_fetch\_array()** example** ``` <?php  $conn = pg_pconnect("dbname=publisher"); if (!$conn) {   echo "An error occurred.\n";   exit; } $result = pg_query($conn, "SELECT author, email FROM authors"); if (!$result) {   echo "An error occurred.\n";   exit; } $arr = pg_fetch_array($result, 0, PGSQL_NUM); echo $arr[0] . " <- Row 1 Author\n"; echo $arr[1] . " <- Row 1 E-mail\n"; // The row parameter is optional; NULL can be passed instead, // to pass a result_type.  Successive calls to pg_fetch_array // will return the next row. $arr = pg_fetch_array($result, NULL, PGSQL_ASSOC); echo $arr["author"] . " <- Row 2 Author\n"; echo $arr["email"] . " <- Row 2 E-mail\n"; $arr = pg_fetch_array($result); echo $arr["author"] . " <- Row 3 Author\n"; echo $arr[1] . " <- Row 3 E-mail\n"; ?> ``` ### See Also * [pg\_fetch\_row()](function.pg-fetch-row) - Get a row as an enumerated array * [pg\_fetch\_object()](function.pg-fetch-object) - Fetch a row as an object * [pg\_fetch\_result()](function.pg-fetch-result) - Returns values from a result instance php imagearc imagearc ======== (PHP 4, PHP 5, PHP 7, PHP 8) imagearc — Draws an arc ### Description ``` imagearc( GdImage $image, int $center_x, int $center_y, int $width, int $height, int $start_angle, int $end_angle, int $color ): bool ``` **imagearc()** draws an arc of circle centered at the given coordinates. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `center_x` x-coordinate of the center. `center_y` y-coordinate of the center. `width` The arc width. `height` The arc height. `start_angle` The arc start angle, in degrees. `end_angle` The arc end angle, in degrees. 0° is located at the three-o'clock position, and the arc is drawn clockwise. `color` A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Drawing a circle with **imagearc()**** ``` <?php // create a 200*200 image $img = imagecreatetruecolor(200, 200); // allocate some colors $white = imagecolorallocate($img, 255, 255, 255); $red   = imagecolorallocate($img, 255,   0,   0); $green = imagecolorallocate($img,   0, 255,   0); $blue  = imagecolorallocate($img,   0,   0, 255); // draw the head imagearc($img, 100, 100, 200, 200,  0, 360, $white); // mouth imagearc($img, 100, 100, 150, 150, 25, 155, $red); // left and then the right eye imagearc($img,  60,  75,  50,  50,  0, 360, $green); imagearc($img, 140,  75,  50,  50,  0, 360, $blue); // output image in the browser header("Content-type: image/png"); imagepng($img); // free memory imagedestroy($img); ?> ``` The above example will output something similar to: ### See Also * [imagefilledarc()](function.imagefilledarc) - Draw a partial arc and fill it * [imageellipse()](function.imageellipse) - Draw an ellipse * [imagefilledellipse()](function.imagefilledellipse) - Draw a filled ellipse php Gmagick::getimagedelay Gmagick::getimagedelay ====================== (PECL gmagick >= Unknown) Gmagick::getimagedelay — Gets the image delay ### Description ``` public Gmagick::getimagedelay(): int ``` Gets the image delay ### Parameters This function has no parameters. ### Return Values Returns the composite operator associated with the image. ### Errors/Exceptions Throws an **GmagickException** on error. php snmp3_real_walk snmp3\_real\_walk ================= (PHP 4, PHP 5, PHP 7, PHP 8) snmp3\_real\_walk — Return all objects including their respective object ID within the specified one ### Description ``` snmp3_real_walk( string $hostname, string $security_name, string $security_level, string $auth_protocol, string $auth_passphrase, string $privacy_protocol, string $privacy_passphrase, array|string $object_id, int $timeout = -1, int $retries = -1 ): array|false ``` The **snmp3\_real\_walk()** function is used to traverse over a number of SNMP objects starting from `object_id` and return not only their values but also their object ids. ### Parameters `hostname` The hostname of the SNMP agent (server). `security_name` the security name, usually some kind of username `security_level` the security level (noAuthNoPriv|authNoPriv|authPriv) `auth_protocol` the authentication protocol (MD5 or SHA) `auth_passphrase` the authentication pass phrase `privacy_protocol` the authentication protocol (`"MD5"`, `"SHA"`, `"SHA256"`, or `"SHA512"`) `privacy_passphrase` the privacy pass phrase `object_id` The SNMP object id. `timeout` The number of microseconds until the first timeout. `retries` The number of times to retry if timeouts occur. ### Return Values Returns an associative array of the SNMP object ids and their values on success or **`false`** on error. In case of an error, an E\_WARNING message is shown. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `auth_protocol` now accepts `"SHA256"` and `"SHA512"` when supported by libnetsnmp. | ### Examples **Example #1 Using **snmp3\_real\_walk()**** ``` <?php  var_export(snmp3_real_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName')); ?> ``` The above will output something like: ``` array ( 'IF-MIB::ifName.1' => 'STRING: lo', 'IF-MIB::ifName.2' => 'STRING: eth0', 'IF-MIB::ifName.3' => 'STRING: eth2', 'IF-MIB::ifName.4' => 'STRING: sit0', 'IF-MIB::ifName.5' => 'STRING: sixxs', ) ``` ### See Also * [snmpwalk()](function.snmpwalk) - Fetch all the SNMP objects from an agent php Memcached::getStats Memcached::getStats =================== (PECL memcached >= 0.1.0) Memcached::getStats — Get server pool statistics ### Description ``` public Memcached::getStats(): array|false ``` **Memcached::getStats()** returns an array containing the state of all available memcache servers. See [» memcache protocol](https://github.com/memcached/memcached/blob/master/doc/protocol.txt) specification for details on these statistics. ### Parameters This function has no parameters. ### Return Values Array of server statistics, one entry per server, or **`false`** on failure. ### Examples **Example #1 **Memcached::getStats()** example** ``` <?php $m = new Memcached(); $m->addServer('localhost', 11211); print_r($m->getStats()); ?> ``` The above example will output something similar to: ``` Array ( [localhost:11211] => Array ( [pid] => 4933 [uptime] => 786123 [threads] => 1 [time] => 1233868010 [pointer_size] => 32 [rusage_user_seconds] => 0 [rusage_user_microseconds] => 140000 [rusage_system_seconds] => 23 [rusage_system_microseconds] => 210000 [curr_items] => 145 [total_items] => 2374 [limit_maxbytes] => 67108864 [curr_connections] => 2 [total_connections] => 151 [connection_structures] => 3 [bytes] => 20345 [cmd_get] => 213343 [cmd_set] => 2381 [get_hits] => 204223 [get_misses] => 9120 [evictions] => 0 [bytes_read] => 9092476 [bytes_written] => 15420512 [version] => 1.2.6 ) ) ``` php ImagickDraw::setStrokePatternURL ImagickDraw::setStrokePatternURL ================================ (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokePatternURL — Sets the pattern used for stroking object outlines ### Description ``` public ImagickDraw::setStrokePatternURL(string $stroke_url): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the pattern used for stroking object outlines. ### Parameters `stroke_url` stroke URL ### Return Values Returns **`true`** on success. php Ds\Set::filter Ds\Set::filter ============== (PECL ds >= 1.0.0) Ds\Set::filter — Creates a new set using a [callable](language.types.callable) to determine which values to include ### Description ``` public Ds\Set::filter(callable $callback = ?): Ds\Set ``` Creates a new set using a [callable](language.types.callable) to determine which values to include. ### Parameters `callback` ``` callback(mixed $value): bool ``` Optional [callable](language.types.callable) which returns **`true`** if the value should be included, **`false`** otherwise. If a callback is not provided, only values which are **`true`** (see [converting to boolean](language.types.boolean#language.types.boolean.casting)) will be included. ### Return Values A new set containing all the values for which either the `callback` returned **`true`**, or all values that convert to **`true`** if a `callback` was not provided. ### Examples **Example #1 **Ds\Set::filter()** example using callback function** ``` <?php $set = new \Ds\Set([1, 2, 3, 4, 5]); var_dump($set->filter(function($value) {     return $value % 2 == 0; })); ?> ``` The above example will output something similar to: ``` object(Ds\Set)#3 (2) { [0]=> int(2) [1]=> int(4) } ``` **Example #2 **Ds\Set::filter()** example without a callback function** ``` <?php $set = new \Ds\Set([0, 1, 'a', true, false]); var_dump($set->filter()); ?> ``` The above example will output something similar to: ``` object(Ds\Set)#2 (3) { [0]=> int(1) [1]=> string(1) "a" [2]=> bool(true) } ``` php NumberFormatter::getErrorCode NumberFormatter::getErrorCode ============================= numfmt\_get\_error\_code ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) NumberFormatter::getErrorCode -- numfmt\_get\_error\_code — Get formatter's last error code ### Description Object-oriented style ``` public NumberFormatter::getErrorCode(): int ``` Procedural style ``` numfmt_get_error_code(NumberFormatter $formatter): int ``` Get error code from the last function performed by the formatter. ### Parameters `formatter` [NumberFormatter](class.numberformatter) object. ### Return Values Returns error code from last formatter call. ### Examples **Example #1 **numfmt\_get\_error\_code()** example** ``` <?php $fmt  = numfmt_create( 'de_DE', NumberFormatter::DECIMAL ); $data = numfmt_format($fmt, 1234567.891234567890000); if(intl_is_failure(numfmt_get_error_code($fmt))) {     report_error("Formatter error"); } ?> ``` **Example #2 OO example** ``` <?php $fmt = new NumberFormatter( 'de_DE', NumberFormatter::DECIMAL ); $fmt->format(1234567.891234567890000); if(intl_is_failure($fmt->getErrorCode())) {     report_error("Formatter error"); } ?> ``` ### See Also * [numfmt\_get\_error\_message()](numberformatter.geterrormessage) - Get formatter's last error message * [intl\_get\_error\_code()](function.intl-get-error-code) - Get the last error code * [intl\_is\_failure()](function.intl-is-failure) - Check whether the given error code indicates failure php IntlChar::hasBinaryProperty IntlChar::hasBinaryProperty =========================== (PHP 7, PHP 8) IntlChar::hasBinaryProperty — Check a binary Unicode property for a code point ### Description ``` public static IntlChar::hasBinaryProperty(int|string $codepoint, int $property): ?bool ``` Checks a binary Unicode property for a code point. Unicode, especially in version 3.2, defines many more properties than the original set in UnicodeData.txt. The properties APIs are intended to reflect Unicode properties as defined in the Unicode Character Database (UCD) and Unicode Technical Reports (UTR). For details about the properties see [» http://www.unicode.org/ucd/](http://www.unicode.org/ucd/). For names of Unicode properties see the UCD file PropertyAliases.txt. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). ### Return Values Returns **`true`** or **`false`** according to the binary Unicode property value for `codepoint`. Also **`false`** if `property` is out of bounds or if the Unicode version does not have data for the property at all, or not for this code point. Returns **`null`** on failure. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_ALPHABETIC)); var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_CASE_SENSITIVE)); var_dump(IntlChar::hasBinaryProperty("A", IntlChar::PROPERTY_BIDI_MIRRORED)); var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_ALPHABETIC)); var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_CASE_SENSITIVE)); var_dump(IntlChar::hasBinaryProperty("[", IntlChar::PROPERTY_BIDI_MIRRORED)); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(false) bool(false) bool(true) ``` ### See Also * [IntlChar::getIntPropertyValue()](intlchar.getintpropertyvalue) - Get the value for a Unicode property for a code point * [IntlChar::getUnicodeVersion()](intlchar.getunicodeversion) - Get the Unicode version php SQLite3Stmt::reset SQLite3Stmt::reset ================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Stmt::reset — Resets the prepared statement ### Description ``` public SQLite3Stmt::reset(): bool ``` Resets the prepared statement to its state prior to execution. All bindings remain intact after reset. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the statement is successfully reset, or **`false`** on failure. php VarnishAdmin::setSecret VarnishAdmin::setSecret ======================= (PECL varnish >= 0.8) VarnishAdmin::setSecret — Set the class secret configuration param ### Description ``` public VarnishAdmin::setSecret(string $secret): void ``` ### Parameters `secret` Connection secret configuration parameter. ### Return Values php quotemeta quotemeta ========= (PHP 4, PHP 5, PHP 7, PHP 8) quotemeta — Quote meta characters ### Description ``` quotemeta(string $string): string ``` Returns a version of str with a backslash character (`\`) before every character that is among these: . \ + \* ? [ ^ ] ( $ ) ### Parameters `string` The input string. ### Return Values Returns the string with meta characters quoted, or **`false`** if an empty string is given as `string`. ### Examples **Example #1 **quotemeta()** example** ``` <?php var_dump(quotemeta('PHP is a popular scripting language. Fast, flexible, and pragmatic.')); ?> ``` The above example will output: ``` string(69) "PHP is a popular scripting language\. Fast, flexible, and pragmatic\." ``` ### Notes > **Note**: This function is binary-safe. > > ### See Also * [addslashes()](function.addslashes) - Quote string with slashes * [addcslashes()](function.addcslashes) - Quote string with slashes in a C style * [htmlentities()](function.htmlentities) - Convert all applicable characters to HTML entities * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities * [nl2br()](function.nl2br) - Inserts HTML line breaks before all newlines in a string * [stripslashes()](function.stripslashes) - Un-quotes a quoted string * [stripcslashes()](function.stripcslashes) - Un-quote string quoted with addcslashes * [preg\_quote()](function.preg-quote) - Quote regular expression characters php EvPeriodic::set EvPeriodic::set =============== (PECL ev >= 0.2.0) EvPeriodic::set — Configures the watcher ### Description ``` public EvPeriodic::set( float $offset , float $interval ): void ``` (Re-)Configures EvPeriodic watcher ### Parameters `offset` The same meaning as for [EvPeriodic::\_\_construct()](evperiodic.construct) . See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) `interval` The same meaning as for [EvPeriodic::\_\_construct()](evperiodic.construct) . See [Periodic watcher operation modes](https://www.php.net/manual/en/ev.periodic-modes.php) ### Return Values No value is returned.
programming_docs
php Ev::sleep Ev::sleep ========= (PECL ev >= 0.2.0) Ev::sleep — Block the process for the given number of seconds ### Description ``` final public static Ev::sleep( float $seconds ): void ``` Block the process for the given number of seconds. ### Parameters `seconds` Fractional number of seconds ### Return Values No value is returned. php SolrInputDocument::__construct SolrInputDocument::\_\_construct ================================ (PECL solr >= 0.9.2) SolrInputDocument::\_\_construct — Constructor ### Description public **SolrInputDocument::\_\_construct**() Constructor. ### Parameters This function has no parameters. ### Return Values None. php Yaf_Request_Abstract::getModuleName Yaf\_Request\_Abstract::getModuleName ===================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::getModuleName — The getModuleName purpose ### Description ``` public Yaf_Request_Abstract::getModuleName(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php The SeekableIterator interface The SeekableIterator interface ============================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) The Seekable iterator. Interface synopsis ------------------ interface **SeekableIterator** extends [Iterator](class.iterator) { /\* Methods \*/ ``` public seek(int $offset): void ``` /\* Inherited methods \*/ ``` public Iterator::current(): mixed ``` ``` public Iterator::key(): mixed ``` ``` public Iterator::next(): void ``` ``` public Iterator::rewind(): void ``` ``` public Iterator::valid(): bool ``` } **Example #1 Basic usage** This example demonstrates creating a custom **SeekableIterator**, seeking to a position and handling an invalid position. ``` <?php class MySeekableIterator implements SeekableIterator {     private $position;     private $array = array(         "first element",         "second element",         "third element",         "fourth element"     );     /* Method required for SeekableIterator interface */     public function seek($position) {       if (!isset($this->array[$position])) {           throw new OutOfBoundsException("invalid seek position ($position)");       }       $this->position = $position;     }     /* Methods required for Iterator interface */          public function rewind() {         $this->position = 0;     }     public function current() {         return $this->array[$this->position];     }     public function key() {         return $this->position;     }     public function next() {         ++$this->position;     }     public function valid() {         return isset($this->array[$this->position]);     } } try {     $it = new MySeekableIterator;     echo $it->current(), "\n";          $it->seek(2);     echo $it->current(), "\n";          $it->seek(1);     echo $it->current(), "\n";          $it->seek(10);      } catch (OutOfBoundsException $e) {     echo $e->getMessage(); } ?> ``` The above example will output something similar to: ``` first element third element second element invalid seek position (10) ``` Table of Contents ----------------- * [SeekableIterator::seek](seekableiterator.seek) — Seeks to a position php The SplHeap class The SplHeap class ================= Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) The SplHeap class provides the main functionalities of a Heap. Class synopsis -------------- abstract class **SplHeap** implements [Iterator](class.iterator), [Countable](class.countable) { /\* Methods \*/ ``` protected compare(mixed $value1, mixed $value2): int ``` ``` public count(): int ``` ``` public current(): mixed ``` ``` public extract(): mixed ``` ``` public insert(mixed $value): bool ``` ``` public isCorrupted(): bool ``` ``` public isEmpty(): bool ``` ``` public key(): int ``` ``` public next(): void ``` ``` public recoverFromCorruption(): bool ``` ``` public rewind(): void ``` ``` public top(): mixed ``` ``` public valid(): bool ``` } Table of Contents ----------------- * [SplHeap::compare](splheap.compare) — Compare elements in order to place them correctly in the heap while sifting up * [SplHeap::count](splheap.count) — Counts the number of elements in the heap * [SplHeap::current](splheap.current) — Return current node pointed by the iterator * [SplHeap::extract](splheap.extract) — Extracts a node from top of the heap and sift up * [SplHeap::insert](splheap.insert) — Inserts an element in the heap by sifting it up * [SplHeap::isCorrupted](splheap.iscorrupted) — Tells if the heap is in a corrupted state * [SplHeap::isEmpty](splheap.isempty) — Checks whether the heap is empty * [SplHeap::key](splheap.key) — Return current node index * [SplHeap::next](splheap.next) — Move to the next node * [SplHeap::recoverFromCorruption](splheap.recoverfromcorruption) — Recover from the corrupted state and allow further actions on the heap * [SplHeap::rewind](splheap.rewind) — Rewind iterator back to the start (no-op) * [SplHeap::top](splheap.top) — Peeks at the node from the top of the heap * [SplHeap::valid](splheap.valid) — Check whether the heap contains more nodes php SQLite3Stmt::bindValue SQLite3Stmt::bindValue ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SQLite3Stmt::bindValue — Binds the value of a parameter to a statement variable ### Description ``` public SQLite3Stmt::bindValue(string|int $param, mixed $value, int $type = SQLITE3_TEXT): bool ``` Binds the value of a parameter to a statement variable. **Caution** Before PHP 7.2.14 and 7.3.0, respectively, once the statement has been executed, [SQLite3Stmt::reset()](sqlite3stmt.reset) needs to be called to be able to change the value of bound parameters. ### Parameters `param` Either a string (for named parameters) or an int (for positional parameters) identifying the statement variable to which the value should be bound. If a named parameter does not start with a colon (`:`) or an at sign (`@`), a colon (`:`) is automatically preprended. Positional parameters start with `1`. `value` The value to bind to a statement variable. `type` The data type of the value to bind. * **`SQLITE3_INTEGER`**: The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. * **`SQLITE3_FLOAT`**: The value is a floating point value, stored as an 8-byte IEEE floating point number. * **`SQLITE3_TEXT`**: The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16-LE). * **`SQLITE3_BLOB`**: The value is a blob of data, stored exactly as it was input. * **`SQLITE3_NULL`**: The value is a NULL value. As of PHP 7.0.7, if `type` is omitted, it is automatically detected from the type of the `value`: bool and int are treated as **`SQLITE3_INTEGER`**, float as **`SQLITE3_FLOAT`**, null as **`SQLITE3_NULL`** and all others as **`SQLITE3_TEXT`**. Formerly, if `type` has been omitted, it has defaulted to **`SQLITE3_TEXT`**. > > **Note**: > > > If `value` is **`null`**, it is always treated as **`SQLITE3_NULL`**, regardless of the given `type`. > > ### Return Values Returns **`true`** if the value is bound to the statement variable, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.4.0 | `param` now also supports the `@param` notation. | ### Examples **Example #1 **SQLite3Stmt::bindValue()** example** ``` <?php $db = new SQLite3(':memory:'); $db->exec('CREATE TABLE foo (id INTEGER, bar STRING)'); $db->exec("INSERT INTO foo (id, bar) VALUES (1, 'This is a test')"); $stmt = $db->prepare('SELECT bar FROM foo WHERE id=:id'); $stmt->bindValue(':id', 1, SQLITE3_INTEGER); $result = $stmt->execute(); var_dump($result->fetchArray(SQLITE3_ASSOC)); ?> ``` The above example will output: ``` array(1) { ["bar"]=> string(14) "This is a test" } ``` ### See Also * [SQLite3Stmt::bindParam()](sqlite3stmt.bindparam) - Binds a parameter to a statement variable * [SQLite3::prepare()](sqlite3.prepare) - Prepares an SQL statement for execution php mysqli_stmt::get_result mysqli\_stmt::get\_result ========================= mysqli\_stmt\_get\_result ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli\_stmt::get\_result -- mysqli\_stmt\_get\_result — Gets a result set from a prepared statement as a [mysqli\_result](class.mysqli-result) object ### Description Object-oriented style ``` public mysqli_stmt::get_result(): mysqli_result|false ``` Procedural style ``` mysqli_stmt_get_result(mysqli_stmt $statement): mysqli_result|false ``` Retrieves a result set from a prepared statement as a [mysqli\_result](class.mysqli-result) object. The data will be fetched from the MySQL server to PHP. This method should be called only for queries which produce a result set. > > **Note**: > > > Available only with [mysqlnd](https://www.php.net/manual/en/book.mysqlnd.php). > > > > **Note**: > > > This function cannot be used together with [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result). Both of these functions retrieve the full result set from the MySQL server. > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values Returns **`false`** on failure. For successful queries which produce a result set, such as `SELECT, SHOW, DESCRIBE` or `EXPLAIN`, **mysqli\_stmt\_get\_result()** will return a [mysqli\_result](class.mysqli-result) object. For other successful queries, **mysqli\_stmt\_get\_result()** will return **`false`**. The [mysqli\_stmt\_errno()](mysqli-stmt.errno) function can be used to distinguish between the two reasons for **`false`**; due to a bug, prior to PHP 7.4.13, [mysqli\_errno()](mysqli.errno) had to be used for this purpose. ### Examples **Example #1 Object-oriented style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1"; $stmt = $mysqli->prepare($query); $stmt->bind_param("s", $continent); $continentList = array('Europe', 'Africa', 'Asia', 'North America'); foreach ($continentList as $continent) {     $stmt->execute();     $result = $stmt->get_result();     while ($row = $result->fetch_array(MYSQLI_NUM)) {         foreach ($row as $r) {             print "$r ";         }         print "\n";     } } ``` **Example #2 Procedural style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, Population, Continent FROM Country WHERE Continent=? ORDER BY Name LIMIT 1"; $stmt = mysqli_prepare($link, $query); mysqli_stmt_bind_param($stmt, "s", $continent); $continentList= array('Europe', 'Africa', 'Asia', 'North America'); foreach ($continentList as $continent) {     mysqli_stmt_execute($stmt);     $result = mysqli_stmt_get_result($stmt);     while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {         foreach ($row as $r) {             print "$r ";         }         print "\n";     } } ``` The above examples will output something similar to: ``` Albania 3401200 Europe Algeria 31471000 Africa Afghanistan 22720000 Asia Anguilla 8000 North America ``` ### See Also * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_result\_metadata()](mysqli-stmt.result-metadata) - Returns result set metadata from a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables * [mysqli\_fetch\_array()](mysqli-result.fetch-array) - Fetch the next row of a result set as an associative, a numeric array, or both * [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) - Stores a result set in an internal buffer php ImagickDraw::setStrokeAntialias ImagickDraw::setStrokeAntialias =============================== (PECL imagick 2, PECL imagick 3) ImagickDraw::setStrokeAntialias — Controls whether stroked outlines are antialiased ### Description ``` public ImagickDraw::setStrokeAntialias(bool $stroke_antialias): bool ``` **Warning**This function is currently not documented; only its argument list is available. Controls whether stroked outlines are antialiased. Stroked outlines are antialiased by default. When antialiasing is disabled stroked pixels are thresholded to determine if the stroke color or underlying canvas color should be used. ### Parameters `stroke_antialias` the antialias setting ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::setStrokeAntialias()** example** ``` <?php function setStrokeAntialias($strokeColor, $fillColor, $backgroundColor) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(1);     $draw->setStrokeAntialias(false);     $draw->line(100, 100, 400, 105);     $draw->line(100, 140, 400, 185);     $draw->setStrokeAntialias(true);     $draw->line(100, 110, 400, 115);     $draw->line(100, 150, 400, 195);     $image = new \Imagick();     $image->newImage(500, 250, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php filter_var filter\_var =========== (PHP 5 >= 5.2.0, PHP 7, PHP 8) filter\_var — Filters a variable with a specified filter ### Description ``` filter_var(mixed $value, int $filter = FILTER_DEFAULT, array|int $options = 0): mixed ``` ### Parameters `value` Value to filter. Note that scalar values are [converted to string](language.types.string#language.types.string.casting) internally before they are filtered. `filter` The ID of the filter to apply. The [Types of filters](https://www.php.net/manual/en/filter.filters.php) manual page lists the available filters. If omitted, **`FILTER_DEFAULT`** will be used, which is equivalent to [**`FILTER_UNSAFE_RAW`**](https://www.php.net/manual/en/filter.filters.sanitize.php). This will result in no filtering taking place by default. `options` Associative array of options or bitwise disjunction of flags. If filter accepts options, flags can be provided in "flags" field of array. For the "callback" filter, [callable](language.types.callable) type should be passed. The callback must accept one argument, the value to be filtered, and return the value after filtering/sanitizing it. ``` <?php // for filters that accept options, use this format $options = array(     'options' => array(         'default' => 3, // value to return if the filter fails         // other options here         'min_range' => 0     ),     'flags' => FILTER_FLAG_ALLOW_OCTAL, ); $var = filter_var('0755', FILTER_VALIDATE_INT, $options); // for filters that only accept flags, you can pass them directly $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE); // for filters that only accept flags, you can also pass as an array $var = filter_var('oops', FILTER_VALIDATE_BOOLEAN,                   array('flags' => FILTER_NULL_ON_FAILURE)); // callback validate filter function foo($value) {     // Expected format: Surname, GivenNames     if (strpos($value, ", ") === false) return false;     list($surname, $givennames) = explode(", ", $value, 2);     $empty = (empty($surname) || empty($givennames));     $notstrings = (!is_string($surname) || !is_string($givennames));     if ($empty || $notstrings) {         return false;     } else {         return $value;     } } $var = filter_var('Doe, Jane Sue', FILTER_CALLBACK, array('options' => 'foo')); ?> ``` ### Return Values Returns the filtered data, or **`false`** if the filter fails. ### Examples **Example #1 A **filter\_var()** example** ``` <?php var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL)); var_dump(filter_var('http://example.com', FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)); ?> ``` The above example will output: ``` string(15) "[email protected]" bool(false) ``` ### See Also * [filter\_var\_array()](function.filter-var-array) - Gets multiple variables and optionally filters them * [filter\_input()](function.filter-input) - Gets a specific external variable by name and optionally filters it * [filter\_input\_array()](function.filter-input-array) - Gets external variables and optionally filters them * [Types of filters](https://www.php.net/manual/en/filter.filters.php) php gc_disable gc\_disable =========== (PHP 5 >= 5.3.0, PHP 7, PHP 8) gc\_disable — Deactivates the circular reference collector ### Description ``` gc_disable(): void ``` Deactivates the circular reference collector, setting [zend.enable\_gc](https://www.php.net/manual/en/info.configuration.php#ini.zend.enable-gc) to `0`. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [Garbage Collection](https://www.php.net/manual/en/features.gc.php) php ReflectionEnumUnitCase::__construct ReflectionEnumUnitCase::\_\_construct ===================================== (PHP 8 >= 8.1.0) ReflectionEnumUnitCase::\_\_construct — Instantiates a [ReflectionEnumUnitCase](class.reflectionenumunitcase) object ### Description public **ReflectionEnumUnitCase::\_\_construct**(object|string `$class`, string `$constant`) ### Parameters `class` An enum instance or a name. `constant` An enum constant name. php mysqli_stmt::next_result mysqli\_stmt::next\_result ========================== mysqli\_stmt\_next\_result ========================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli\_stmt::next\_result -- mysqli\_stmt\_next\_result — Reads the next result from a multiple query ### Description Object-oriented style ``` public mysqli_stmt::next_result(): bool ``` Procedural style: ``` mysqli_stmt_next_result(mysqli_stmt $statement): bool ``` Reads the next result from a multiple query. > > **Note**: > > > Prior to PHP 8.1.0, available only with [mysqlnd](https://www.php.net/manual/en/book.mysqlnd.php). > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Now also available when linking against libmysqlclient. | ### See Also * [mysqli\_stmt::more\_results()](mysqli-stmt.more-results) - Check if there are more query results from a multiple query * [mysqli::multi\_query()](mysqli.multi-query) - Performs one or more queries on the database php Gmagick::queryfonts Gmagick::queryfonts =================== (PECL gmagick >= Unknown) Gmagick::queryfonts — Returns the configured fonts ### Description ``` public Gmagick::queryfonts(string $pattern = "*"): array ``` Returns fonts supported by Gmagick. ### Parameters This function has no parameters. ### Return Values The Gmagick object on success ### Errors/Exceptions Throws an **GmagickException** on error. php None Comparing Objects ----------------- When using the comparison operator (`==`), object variables are compared in a simple manner, namely: Two object instances are equal if they have the same attributes and values (values are compared with `==`), and are instances of the same class. When using the identity operator (`===`), object variables are identical if and only if they refer to the same instance of the same class. An example will clarify these rules. **Example #1 Example of object comparison** ``` <?php function bool2str($bool) {     if ($bool === false) {         return 'FALSE';     } else {         return 'TRUE';     } } function compareObjects(&$o1, &$o2) {     echo 'o1 == o2 : ' . bool2str($o1 == $o2) . "\n";     echo 'o1 != o2 : ' . bool2str($o1 != $o2) . "\n";     echo 'o1 === o2 : ' . bool2str($o1 === $o2) . "\n";     echo 'o1 !== o2 : ' . bool2str($o1 !== $o2) . "\n"; } class Flag {     public $flag;     function __construct($flag = true) {         $this->flag = $flag;     } } class OtherFlag {     public $flag;     function __construct($flag = true) {         $this->flag = $flag;     } } $o = new Flag(); $p = new Flag(); $q = $o; $r = new OtherFlag(); echo "Two instances of the same class\n"; compareObjects($o, $p); echo "\nTwo references to the same instance\n"; compareObjects($o, $q); echo "\nInstances of two different classes\n"; compareObjects($o, $r); ?> ``` The above example will output: ``` Two instances of the same class o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : FALSE o1 !== o2 : TRUE Two references to the same instance o1 == o2 : TRUE o1 != o2 : FALSE o1 === o2 : TRUE o1 !== o2 : FALSE Instances of two different classes o1 == o2 : FALSE o1 != o2 : TRUE o1 === o2 : FALSE o1 !== o2 : TRUE ``` > > **Note**: > > > Extensions can define own rules for their objects comparison (`==`). > >
programming_docs
php Gmagick::flopimage Gmagick::flopimage ================== (PECL gmagick >= Unknown) Gmagick::flopimage — Creates a horizontal mirror image ### Description ``` public Gmagick::flopimage(): Gmagick ``` Creates a horizontal mirror image by reflecting the pixels around the central y-axis. ### Parameters This function has no parameters. ### Return Values The flopped [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. ### See Also * [Gmagick::flipimage()](gmagick.flipimage) - Creates a vertical mirror image php imageflip imageflip ========= (PHP 5 >= 5.5.0, PHP 7, PHP 8) imageflip — Flips an image using a given mode ### Description ``` imageflip(GdImage $image, int $mode): bool ``` Flips the `image` image using the given `mode`. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `mode` Flip mode, this can be one of the **`IMG_FLIP_*`** constants: | Constant | Meaning | | --- | --- | | **`IMG_FLIP_HORIZONTAL`** | Flips the image horizontally. | | **`IMG_FLIP_VERTICAL`** | Flips the image vertically. | | **`IMG_FLIP_BOTH`** | Flips the image both horizontally and vertically. | ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Flips an image vertically** This example uses the **`IMG_FLIP_VERTICAL`** constant. ``` <?php // File $filename = 'phplogo.png'; // Content type header('Content-type: image/png'); // Load $im = imagecreatefrompng($filename); // Flip it vertically imageflip($im, IMG_FLIP_VERTICAL); // Output imagejpeg($im); imagedestroy($im); ?> ``` The above example will output something similar to: **Example #2 Flips the image horizontally** This example uses the **`IMG_FLIP_HORIZONTAL`** constant. ``` <?php // File $filename = 'phplogo.png'; // Content type header('Content-type: image/png'); // Load $im = imagecreatefrompng($filename); // Flip it horizontally imageflip($im, IMG_FLIP_HORIZONTAL); // Output imagejpeg($im); imagedestroy($im); ?> ``` The above example will output something similar to: php None Basics ------ PHP reports errors in response to a number of internal error conditions. These may be used to signal a number of different conditions, and can be displayed and/or logged as required. Every error that PHP generates includes a type. A [list of these error types](https://www.php.net/manual/en/errorfunc.constants.php) is available, along with a short description of their behaviour and how they can be caused. ### Handling errors with PHP If no error handler is set, then PHP will handle any errors that occur according to its configuration. Which errors are reported and which are ignored is controlled by the [`error_reporting`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) php.ini directive, or at runtime by calling [error\_reporting()](function.error-reporting). It is strongly recommended that the configuration directive be set, however, as some errors can occur before execution of your script begins. In a development environment, you should always set [`error_reporting`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) to **`E_ALL`**, as you need to be aware of and fix the issues raised by PHP. In production, you may wish to set this to a less verbose level such as `E_ALL & ~E_NOTICE & ~E_DEPRECATED`, but in many cases **`E_ALL`** is also appropriate, as it may provide early warning of potential issues. What PHP does with these errors depends on two further php.ini directives. [`display_errors`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) controls whether the error is shown as part of the script's output. This should always be disabled in a production environment, as it can include confidential information such as database passwords, but is often useful to enable in development, as it ensures immediate reporting of issues. In addition to displaying errors, PHP can log errors when the [`log_errors`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.log-errors) directive is enabled. This will log any errors to the file or syslog defined by [`error_log`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-log). This can be extremely useful in a production environment, as you can log errors that occur and then generate reports based on those errors. ### User error handlers If PHP's default error handling is inadequate, you can also handle many types of error with your own custom error handler by installing it with [set\_error\_handler()](function.set-error-handler). While some error types cannot be handled this way, those that can be handled can then be handled in the way that your script sees fit: for example, this can be used to show a custom error page to the user and then report more directly than via a log, such as by sending an e-mail. php Yaf_Session::key Yaf\_Session::key ================= (Yaf >=1.0.0) Yaf\_Session::key — The key purpose ### Description ``` public Yaf_Session::key(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Yaf_Controller_Abstract::getResponse Yaf\_Controller\_Abstract::getResponse ====================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::getResponse — Retrieve current response object ### Description ``` public Yaf_Controller_Abstract::getResponse(): Yaf_Response_Abstract ``` retrieve current response object ### Parameters This function has no parameters. ### Return Values [Yaf\_Response\_Abstract](class.yaf-response-abstract) instance php None Returning values ---------------- Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called. See [return](function.return) for more information. > > **Note**: > > > If the [return](function.return) is omitted the value **`null`** will be returned. > > ### Use of return **Example #1 Use of [return](function.return)** ``` <?php function square($num) {     return $num * $num; } echo square(4);   // outputs '16'. ?> ``` A function can not return multiple values, but similar results can be obtained by returning an array. **Example #2 Returning an array to get multiple values** ``` <?php function small_numbers() {     return [0, 1, 2]; } // Array destructuring will collect each member of the array individually [$zero, $one, $two] = small_numbers(); // Prior to 7.1.0, the only equivalent alternative is using list() construct list($zero, $one, $two) = small_numbers(); ?> ``` To return a reference from a function, use the reference operator & in both the function declaration and when assigning the returned value to a variable: **Example #3 Returning a reference from a function** ``` <?php function &returns_reference() {     return $someref; } $newref =& returns_reference(); ?> ``` For more information on references, please check out [References Explained](https://www.php.net/manual/en/language.references.php). php ReflectionParameter::isCallable ReflectionParameter::isCallable =============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionParameter::isCallable — Returns whether parameter MUST be callable **Warning**This function has been *DEPRECATED* as of PHP 8.0.0. Relying on this function is highly discouraged. See the example below for an alternative way to derive this information. ### Description ``` public ReflectionParameter::isCallable(): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the parameter is [callable](language.types.callable), **`false`** if it is not or **`null`** on failure. ### Examples **Example #1 PHP 8.0.0 equivalent** As of PHP 8.0.0, the following code will report if a type supports callables, including as part of a union. ``` <?php function declaresCallable(ReflectionParameter $reflectionParameter): bool {     $reflectionType = $reflectionParameter->getType();     if (!$reflectionType) return false;     $types = $reflectionType instanceof ReflectionUnionType         ? $reflectionType->getTypes()         : [$reflectionType];    return in_array('callable', array_map(fn(ReflectionNamedType $t) => $t->getName(), $types)); } ?> ``` php LimitIterator::key LimitIterator::key ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) LimitIterator::key — Get current key ### Description ``` public LimitIterator::key(): mixed ``` Gets the key for the current item in the inner [Iterator](class.iterator). ### Parameters This function has no parameters. ### Return Values Returns the key for the current item. ### See Also * [LimitIterator::getPosition()](limititerator.getposition) - Return the current position * [LimitIterator::current()](limititerator.current) - Get current element * [LimitIterator::next()](limititerator.next) - Move the iterator forward * [LimitIterator::rewind()](limititerator.rewind) - Rewind the iterator to the specified starting offset * [LimitIterator::seek()](limititerator.seek) - Seek to the given position * [LimitIterator::valid()](limititerator.valid) - Check whether the current element is valid php The ImagickPixelIterator class The ImagickPixelIterator class ============================== Class synopsis -------------- (PECL imagick 2, PECL imagick 3) class **ImagickPixelIterator** { ``` public clear(): bool ``` ``` public __construct(Imagick $wand) ``` ``` public destroy(): bool ``` ``` public getCurrentIteratorRow(): array ``` ``` public getIteratorRow(): int ``` ``` public getNextIteratorRow(): array ``` ``` public getPreviousIteratorRow(): array ``` ``` public newPixelIterator(Imagick $wand): bool ``` ``` public newPixelRegionIterator( Imagick $wand, int $x, int $y, int $columns, int $rows ): bool ``` ``` public resetIterator(): bool ``` ``` public setIteratorFirstRow(): bool ``` ``` public setIteratorLastRow(): bool ``` ``` public setIteratorRow(int $row): bool ``` ``` public syncIterator(): bool ``` } Table of Contents ----------------- * [ImagickPixelIterator::clear](imagickpixeliterator.clear) — Clear resources associated with a PixelIterator * [ImagickPixelIterator::\_\_construct](imagickpixeliterator.construct) — The ImagickPixelIterator constructor * [ImagickPixelIterator::destroy](imagickpixeliterator.destroy) — Deallocates resources associated with a PixelIterator * [ImagickPixelIterator::getCurrentIteratorRow](imagickpixeliterator.getcurrentiteratorrow) — Returns the current row of ImagickPixel objects * [ImagickPixelIterator::getIteratorRow](imagickpixeliterator.getiteratorrow) — Returns the current pixel iterator row * [ImagickPixelIterator::getNextIteratorRow](imagickpixeliterator.getnextiteratorrow) — Returns the next row of the pixel iterator * [ImagickPixelIterator::getPreviousIteratorRow](imagickpixeliterator.getpreviousiteratorrow) — Returns the previous row * [ImagickPixelIterator::newPixelIterator](imagickpixeliterator.newpixeliterator) — Returns a new pixel iterator * [ImagickPixelIterator::newPixelRegionIterator](imagickpixeliterator.newpixelregioniterator) — Returns a new pixel iterator * [ImagickPixelIterator::resetIterator](imagickpixeliterator.resetiterator) — Resets the pixel iterator * [ImagickPixelIterator::setIteratorFirstRow](imagickpixeliterator.setiteratorfirstrow) — Sets the pixel iterator to the first pixel row * [ImagickPixelIterator::setIteratorLastRow](imagickpixeliterator.setiteratorlastrow) — Sets the pixel iterator to the last pixel row * [ImagickPixelIterator::setIteratorRow](imagickpixeliterator.setiteratorrow) — Set the pixel iterator row * [ImagickPixelIterator::syncIterator](imagickpixeliterator.synciterator) — Syncs the pixel iterator php ReflectionGenerator::getFunction ReflectionGenerator::getFunction ================================ (PHP 7, PHP 8) ReflectionGenerator::getFunction — Gets the function name of the generator ### Description ``` public ReflectionGenerator::getFunction(): ReflectionFunctionAbstract ``` Enables the function name of the generator to be obtained by returning a class derived from [ReflectionFunctionAbstract](class.reflectionfunctionabstract). ### Parameters This function has no parameters. ### Return Values Returns a [ReflectionFunctionAbstract](class.reflectionfunctionabstract) class. This will be [ReflectionFunction](class.reflectionfunction) for functions, or [ReflectionMethod](class.reflectionmethod) for methods. ### Examples **Example #1 **ReflectionGenerator::getFunction()** example** ``` <?php function gen() {     yield 1; } $gen = gen(); $reflectionGen = new ReflectionGenerator($gen); var_dump($reflectionGen->getFunction()); ``` The above example will output something similar to: ``` object(ReflectionFunction)#3 (1) { ["name"]=> string(3) "gen" } ``` ### See Also * [ReflectionGenerator::getThis()](reflectiongenerator.getthis) - Gets the $this value of the generator * [ReflectionGenerator::getTrace()](reflectiongenerator.gettrace) - Gets the trace of the executing generator php ReflectionReference::__construct ReflectionReference::\_\_construct ================================== (No version information available, might only be in Git) ReflectionReference::\_\_construct — Private constructor to disallow direct instantiation ### Description private **ReflectionReference::\_\_construct**() ### Parameters This function has no parameters. php ReflectionMethod::export ReflectionMethod::export ======================== (PHP 5, PHP 7) ReflectionMethod::export — Export a reflection method **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionMethod::export(string $class, string $name, bool $return = false): string ``` Exports a ReflectionMethod. ### Parameters `class` The class name. `name` The name of the method. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values If the `return` parameter is set to **`true`**, then the export is returned as a string, otherwise **`null`** is returned. ### See Also * [ReflectionMethod::\_\_construct()](reflectionmethod.construct) - Constructs a ReflectionMethod * [ReflectionMethod::\_\_toString()](reflectionmethod.tostring) - Returns the string representation of the Reflection method object php sem_release sem\_release ============ (PHP 4, PHP 5, PHP 7, PHP 8) sem\_release — Release a semaphore ### Description ``` sem_release(SysvSemaphore $semaphore): bool ``` **sem\_release()** releases the semaphore if it is currently acquired by the calling process, otherwise a warning is generated. After releasing the semaphore, [sem\_acquire()](function.sem-acquire) may be called to re-acquire it. ### Parameters `semaphore` A Semaphore as returned by [sem\_get()](function.sem-get). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `semaphore` expects a [SysvSemaphore](class.sysvsemaphore) instance now; previously, a resource was expected. | ### See Also * [sem\_get()](function.sem-get) - Get a semaphore id * [sem\_acquire()](function.sem-acquire) - Acquire a semaphore php http_build_query http\_build\_query ================== (PHP 5, PHP 7, PHP 8) http\_build\_query — Generate URL-encoded query string ### Description ``` http_build_query( array|object $data, string $numeric_prefix = "", ?string $arg_separator = null, int $encoding_type = PHP_QUERY_RFC1738 ): string ``` Generates a URL-encoded query string from the associative (or indexed) array provided. ### Parameters `data` May be an array or object containing properties. If `data` is an array, it may be a simple one-dimensional structure, or an array of arrays (which in turn may contain other arrays). If `data` is an object, then only public properties will be incorporated into the result. `numeric_prefix` If numeric indices are used in the base array and this parameter is provided, it will be prepended to the numeric index for elements in the base array only. This is meant to allow for legal variable names when the data is decoded by PHP or another CGI application later on. `arg_separator` [arg\_separator.output](https://www.php.net/manual/en/ini.core.php#ini.arg-separator.output) is used to separate arguments but may be overridden by specifying this parameter. `encoding_type` By default, **`PHP_QUERY_RFC1738`**. If `encoding_type` is **`PHP_QUERY_RFC1738`**, then encoding is performed per [» RFC 1738](http://www.faqs.org/rfcs/rfc1738) and the `application/x-www-form-urlencoded` media type, which implies that spaces are encoded as plus (`+`) signs. If `encoding_type` is **`PHP_QUERY_RFC3986`**, then encoding is performed according to [» RFC 3986](http://www.faqs.org/rfcs/rfc3986), and spaces will be percent encoded (`%20`). ### Return Values Returns a URL-encoded string. ### Examples **Example #1 Simple usage of **http\_build\_query()**** ``` <?php $data = array(     'foo' => 'bar',     'baz' => 'boom',     'cow' => 'milk',     'null' => null,     'php' => 'hypertext processor' ); echo http_build_query($data) . "\n"; echo http_build_query($data, '', '&amp;'); ?> ``` The above example will output: ``` foo=bar&baz=boom&cow=milk&php=hypertext+processor foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor ``` **Example #2 **http\_build\_query()** with numerically index elements.** ``` <?php $data = array('foo', 'bar', 'baz', null, 'boom', 'cow' => 'milk', 'php' => 'hypertext processor'); echo http_build_query($data) . "\n"; echo http_build_query($data, 'myvar_'); ?> ``` The above example will output: ``` 0=foo&1=bar&2=baz&4=boom&cow=milk&php=hypertext+processor myvar_0=foo&myvar_1=bar&myvar_2=baz&myvar_4=boom&cow=milk&php=hypertext+processor ``` **Example #3 **http\_build\_query()** with complex arrays** ``` <?php $data = array(     'user' => array(         'name' => 'Bob Smith',         'age'  => 47,         'sex'  => 'M',         'dob'  => '5/12/1956'     ),     'pastimes' => array('golf', 'opera', 'poker', 'rap'),     'children' => array(         'bobby' => array('age'=>12, 'sex'=>'M'),         'sally' => array('age'=>8, 'sex'=>'F')     ),     'CEO' ); echo http_build_query($data, 'flags_'); ?> ``` this will output : (word wrapped for readability) ``` user%5Bname%5D=Bob+Smith&user%5Bage%5D=47&user%5Bsex%5D=M& user%5Bdob%5D=5%2F12%2F1956&pastimes%5B0%5D=golf&pastimes%5B1%5D=opera& pastimes%5B2%5D=poker&pastimes%5B3%5D=rap&children%5Bbobby%5D%5Bage%5D=12& children%5Bbobby%5D%5Bsex%5D=M&children%5Bsally%5D%5Bage%5D=8& children%5Bsally%5D%5Bsex%5D=F&flags_0=CEO ``` > > **Note**: > > > Only the numerically indexed element in the base array "CEO" received a prefix. The other numeric indices, found under pastimes, do not require a string prefix to be legal variable names. > > **Example #4 Using **http\_build\_query()** with an object** ``` <?php class parentClass {     public    $pub      = 'publicParent';     protected $prot     = 'protectedParent';     private   $priv     = 'privateParent';     public    $pub_bar  = null;     protected $prot_bar = null;     private   $priv_bar = null;     public function __construct(){         $this->pub_bar  = new childClass();         $this->prot_bar = new childClass();         $this->priv_bar = new childClass();     } } class childClass {     public    $pub  = 'publicChild';     protected $prot = 'protectedChild';     private   $priv = 'privateChild'; } $parent = new parentClass(); echo http_build_query($parent); ?> ``` The above example will output: ``` pub=publicParent&pub_bar%5Bpub%5D=publicChild ``` ### See Also * [parse\_str()](function.parse-str) - Parses the string into variables * [parse\_url()](function.parse-url) - Parse a URL and return its components * [urlencode()](function.urlencode) - URL-encodes string * [array\_walk()](function.array-walk) - Apply a user supplied function to every member of an array
programming_docs
php WeakMap::offsetSet WeakMap::offsetSet ================== (PHP 8) WeakMap::offsetSet — Updates the map with a new key-value pair ### Description ``` public WeakMap::offsetSet(object $object, mixed $value): void ``` Updates the map with a new key-value pair. If the key already existed in the map, the old value is replaced with the new. ### Parameters `object` The object serving as key of the key-value pair. `value` The arbitrary data serving as value of the key-value pair. ### Return Values No value is returned. php QuickHashIntHash::loadFromFile QuickHashIntHash::loadFromFile ============================== (PECL quickhash >= Unknown) QuickHashIntHash::loadFromFile — This factory method creates a hash from a file ### Description ``` public static QuickHashIntHash::loadFromFile(string $filename, int $options = ?): QuickHashIntHash ``` This factory method creates a new hash from a definition file on disk. The file format consists of a signature `'QH\0x11\0'`, the number of elements as a 32 bit signed integer in system Endianness, followed by 32 bit signed integers packed together in the Endianness that the system that the code runs on uses. For each hash element there are two 32 bit signed integers stored. The first of each element is the key, and the second is the value belonging to the key. An example could be: **Example #1 QuickHash IntHash file format** ``` 00000000 51 48 11 00 02 00 00 00 01 00 00 00 01 00 00 00 |QH..............| 00000010 03 00 00 00 09 00 00 00 |........| 00000018 ``` **Example #2 QuickHash IntHash file format** ``` header signature ('QH'; key type: 1; value type: 1; filler: \0x00) 00000000 51 48 11 00 number of elements: 00000004 02 00 00 00 data string: 00000000 01 00 00 00 01 00 00 00 03 00 00 00 09 00 00 00 key/value 1 (key = 1, value = 1) 01 00 00 00 01 00 00 00 key/value 2 (key = 3, value = 9) 03 00 00 00 09 00 00 00 ``` ### Parameters `filename` The filename of the file to read the hash from. `options` The same options that the class' constructor takes; except that the size option is ignored. It is automatically calculated to be the same as the number of entries in the hash, rounded up to the nearest power of two with a maximum limit of `4194304`. ### Return Values Returns a new [QuickHashIntHash](class.quickhashinthash). ### Examples **Example #3 **QuickHashIntHash::loadFromFile()** example** ``` <?php $file = dirname( __FILE__ ) . "/simple.hash"; $hash = QuickHashIntHash::loadFromFile(     $file,     QuickHashIntHash::DO_NOT_USE_ZEND_ALLOC ); foreach( range( 0, 0x0f ) as $key ) {     printf( "Key %3d (%2x) is %s\n",         $key, $key,         $hash->exists( $key ) ? 'set' : 'unset'     ); } ?> ``` The above example will output something similar to: ``` Key 0 ( 0) is unset Key 1 ( 1) is set Key 2 ( 2) is set Key 3 ( 3) is set Key 4 ( 4) is unset Key 5 ( 5) is set Key 6 ( 6) is unset Key 7 ( 7) is set Key 8 ( 8) is unset Key 9 ( 9) is unset Key 10 ( a) is unset Key 11 ( b) is set Key 12 ( c) is unset Key 13 ( d) is set Key 14 ( e) is unset Key 15 ( f) is unset ``` php tidy::repairString tidy::repairString ================== tidy\_repair\_string ==================== (PHP 5, PHP 7, PHP 8, PECL tidy >= 0.7.0) tidy::repairString -- tidy\_repair\_string — Repair a string using an optionally provided configuration file ### Description Object-oriented style ``` public static tidy::repairString(string $string, array|string|null $config = null, ?string $encoding = null): string|false ``` Procedural style ``` tidy_repair_string(string $string, array|string|null $config = null, ?string $encoding = null): string|false ``` Repairs the given string. ### Parameters `string` The data to be repaired. `config` The config `config` can be passed either as an array or as a string. If a string is passed, it is interpreted as the name of the configuration file, otherwise, it is interpreted as the options themselves. Check [» http://api.html-tidy.org/#quick-reference](http://api.html-tidy.org/#quick-reference) for an explanation about each option. `encoding` The `encoding` parameter sets the encoding for input/output documents. The possible values for encoding are: `ascii`, `latin0`, `latin1`, `raw`, `utf8`, `iso2022`, `mac`, `win1252`, `ibm858`, `utf16`, `utf16le`, `utf16be`, `big5`, and `shiftjis`. ### Return Values Returns the repaired string, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **tidy::repairString()** is a static method now. | | 8.0.0 | `config` and `encoding` are nullable now. | | 8.0.0 | This function no longer accepts the `useIncludePath` parameter. | ### Examples **Example #1 **tidy::repairString()** example** ``` <?php ob_start(); ?> <html>   <head>     <title>test</title>   </head>   <body>     <p>error</i>   </body> </html> <?php $buffer = ob_get_clean(); $tidy = new tidy(); $clean = $tidy->repairString($buffer); echo $clean; ?> ``` The above example will output: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN"> <html> <head> <title>test</title> </head> <body> <p>error</p> </body> </html> ``` ### See Also * [tidy::parseFile()](tidy.parsefile) - Parse markup in file or URI * [tidy::parseString()](tidy.parsestring) - Parse a document stored in a string * [tidy::repairFile()](tidy.repairfile) - Repair a file and return it as a string php sqlsrv_execute sqlsrv\_execute =============== (No version information available, might only be in Git) sqlsrv\_execute — Executes a statement prepared with [sqlsrv\_prepare()](function.sqlsrv-prepare) ### Description ``` sqlsrv_execute(resource $stmt): bool ``` Executes a statement prepared with [sqlsrv\_prepare()](function.sqlsrv-prepare). This function is ideal for executing a prepared statement multiple times with different parameter values. ### Parameters `stmt` A statement resource returned by [sqlsrv\_prepare()](function.sqlsrv-prepare). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **sqlsrv\_execute()** example** This example demonstrates how to prepare a statement with [sqlsrv\_prepare()](function.sqlsrv-prepare) and re-execute it multiple times (with different parameter values) using **sqlsrv\_execute()**. ``` <?php $serverName = "serverName\sqlexpress"; $connectionInfo = array( "Database"=>"dbName", "UID"=>"username", "PWD"=>"password"); $conn = sqlsrv_connect( $serverName, $connectionInfo); if( $conn === false) {     die( print_r( sqlsrv_errors(), true)); } $sql = "UPDATE Table_1         SET OrderQty = ?         WHERE SalesOrderID = ?"; // Initialize parameters and prepare the statement.  // Variables $qty and $id are bound to the statement, $stmt. $qty = 0; $id = 0; $stmt = sqlsrv_prepare( $conn, $sql, array( &$qty, &$id)); if( !$stmt ) {     die( print_r( sqlsrv_errors(), true)); } // Set up the SalesOrderDetailID and OrderQty information.  // This array maps the order ID to order quantity in key=>value pairs. $orders = array( 1=>10, 2=>20, 3=>30); // Execute the statement for each order. foreach( $orders as $id => $qty) {     // Because $id and $qty are bound to $stmt1, their updated     // values are used with each execution of the statement.      if( sqlsrv_execute( $stmt ) === false ) {           die( print_r( sqlsrv_errors(), true));     } } ?> ``` ### Notes When you prepare a statement that uses variables as parameters, the variables are bound to the statement. This means that if you update the values of the variables, the next time you execute the statement it will run with updated parameter values. For statements that you plan to execute only once, use [sqlsrv\_query()](function.sqlsrv-query). ### See Also * [sqlsrv\_prepare()](function.sqlsrv-prepare) - Prepares a query for execution * [sqlsrv\_query()](function.sqlsrv-query) - Prepares and executes a query php DatePeriod::getRecurrences DatePeriod::getRecurrences ========================== (PHP 7 >= 7.2.17/7.3.4, PHP 8) DatePeriod::getRecurrences — Gets the number of recurrences ### Description Object-oriented style ``` public DatePeriod::getRecurrences(): ?int ``` Get the number of recurrences. ### Parameters This function has no parameters. ### Return Values The number of recurrences as set by explicitly passing the `$recurrences` to the contructor of the [DatePeriod](class.dateperiod) class, or **`null`** otherwise. ### Examples **Example #1 Different values for **DatePeriod::getRecurrences()**** ``` <?php $start = new DateTime('2018-12-31 00:00:00'); $end   = new DateTime('2021-12-31 00:00:00'); $interval = new DateInterval('P1M'); $recurrences = 5; // recurrences explicitly set through the constructor $period = new DatePeriod($start, $interval, $recurrences, DatePeriod::EXCLUDE_START_DATE); echo $period->getRecurrences(), "\n"; $period = new DatePeriod($start, $interval, $recurrences); echo $period->getRecurrences(), "\n"; $period = new DatePeriod($start, $interval, $recurrences, DatePeriod::INCLUDE_END_DATE); echo $period->getRecurrences(), "\n\n"; // recurrences not set in the constructor $period = new DatePeriod($start, $interval, $end); var_dump($period->getRecurrences()); $period = new DatePeriod($start, $interval, $end, DatePeriod::EXCLUDE_START_DATE); var_dump($period->getRecurrences()); ?> ``` The above example will output: 5 5 5 NULL NULL ### See Also * [DatePeriod::$recurrences](class.dateperiod#dateperiod.props.recurrences) php SoapServer::setObject SoapServer::setObject ===================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) SoapServer::setObject — Sets the object which will be used to handle SOAP requests ### Description ``` public SoapServer::setObject(object $object): void ``` This sets a specific object as the handler for SOAP requests, rather than just a class as in [SoapServer::setClass()](soapserver.setclass). ### Parameters `object` The object to handle the requests. ### Return Values No value is returned. ### See Also * [SoapServer::setClass()](soapserver.setclass) - Sets the class which handles SOAP requests php ReflectionMethod::isFinal ReflectionMethod::isFinal ========================= (PHP 5, PHP 7, PHP 8) ReflectionMethod::isFinal — Checks if method is final ### Description ``` public ReflectionMethod::isFinal(): bool ``` Checks if the method is final. ### Parameters This function has no parameters. ### Return Values **`true`** if the method is final, otherwise **`false`** ### See Also * [ReflectionMethod::isStatic()](reflectionmethod.isstatic) - Checks if method is static php Ds\Deque::allocate Ds\Deque::allocate ================== (PECL ds >= 1.0.0) Ds\Deque::allocate — Allocates enough memory for a required capacity ### Description ``` public Ds\Deque::allocate(int $capacity): void ``` Ensures that enough memory is allocated for a required capacity. This removes the need to reallocate the internal as values are added. ### Parameters `capacity` The number of values for which capacity should be allocated. > > **Note**: > > > Capacity will stay the same if this value is less than or equal to the current capacity. > > > > **Note**: > > > Capacity will always be rounded up to the nearest power of 2. > > ### Return Values No value is returned. ### Examples **Example #1 **Ds\Deque::allocate()** example** ``` <?php $deque = new \Ds\Deque(); var_dump($deque->capacity()); $deque->allocate(100); var_dump($deque->capacity()); ?> ``` The above example will output something similar to: ``` int(8) int(128) ``` php EventBufferEvent::write EventBufferEvent::write ======================= (PECL event >= 1.2.6-beta) EventBufferEvent::write — Adds data to a buffer event's output buffer ### Description ``` public EventBufferEvent::write( string $data ): bool ``` Adds `data` to a buffer event's output buffer ### Parameters `data` Data to be added to the underlying buffer. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBufferEvent::writeBuffer()](eventbufferevent.writebuffer) - Adds contents of the entire buffer to a buffer event's output buffer php snmp3_walk snmp3\_walk =========== (PHP 4, PHP 5, PHP 7, PHP 8) snmp3\_walk — Fetch all the SNMP objects from an agent ### Description ``` snmp3_walk( string $hostname, string $security_name, string $security_level, string $auth_protocol, string $auth_passphrase, string $privacy_protocol, string $privacy_passphrase, array|string $object_id, int $timeout = -1, int $retries = -1 ): array|false ``` **snmp3\_walk()** function is used to read all the values from an SNMP agent specified by the `hostname`. Even if the security level does not use an auth or priv protocol/password valid values have to be specified. ### Parameters `hostname` The hostname of the SNMP agent (server). `security_name` the security name, usually some kind of username `security_level` the security level (noAuthNoPriv|authNoPriv|authPriv) `auth_protocol` the authentication protocol (`"MD5"`, `"SHA"`, `"SHA256"`, or `"SHA512"`) `auth_passphrase` the authentication pass phrase `privacy_protocol` the privacy protocol (DES or AES) `privacy_passphrase` the privacy pass phrase `object_id` If **`null`**, `object_id` is taken as the root of the SNMP objects tree and all objects under that tree are returned as an array. If `object_id` is specified, all the SNMP objects below that `object_id` are returned. `timeout` The number of microseconds until the first timeout. `retries` The number of times to retry if timeouts occur. ### Return Values Returns an array of SNMP object values starting from the `object_id` as root or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `auth_protocol` now accepts `"SHA256"` and `"SHA512"` when supported by libnetsnmp. | ### Examples **Example #1 **snmp3\_walk()** Example** ``` <?php $ret = snmp3_walk('localhost', 'james', 'authPriv', 'SHA', 'secret007', 'AES', 'secret007', 'IF-MIB::ifName'); var_export($ret); ?> ``` Above function call would return all the SNMP objects from the SNMP agent running on localhost: ``` array ( 0 => 'STRING: lo', 1 => 'STRING: eth0', 2 => 'STRING: eth2', 3 => 'STRING: sit0', 4 => 'STRING: sixxs', ) ``` ### See Also * [snmp3\_real\_walk()](function.snmp3-real-walk) - Return all objects including their respective object ID within the specified one php uopz_del_function uopz\_del\_function =================== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_del\_function — Deletes previously added function or method ### Description ``` uopz_del_function(string $function): bool ``` ``` uopz_del_function(string $class, string $function, int &$all = true): bool ``` Deletes a previously added function or method. ### Parameters `class` The name of the class. `function` The name of the function or method. `all` Whether all classes that descend from `class` will also be affected. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions **uopz\_del\_function()** throws a [RuntimeException](class.runtimeexception) if the function or method to delete has not been added by [uopz\_add\_function()](function.uopz-add-function). ### Examples **Example #1 Basic **uopz\_del\_function()** Usage** ``` <?php uopz_add_function('foo', function () {echo 'bar';}); var_dump(function_exists('foo')); uopz_del_function('foo'); var_dump(function_exists('foo')); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### See Also * [uopz\_add\_function()](function.uopz-add-function) - Adds non-existent function or method * [uopz\_unset\_return()](function.uopz-unset-return) - Unsets a previously set return value for a function php openal_listener_get openal\_listener\_get ===================== (PECL openal >= 0.1.0) openal\_listener\_get — Retrieve a listener property ### Description ``` openal_listener_get(int $property): mixed ``` ### Parameters `property` Property to retrieve, one of: **`AL_GAIN`** (float), **`AL_POSITION`** (array(float,float,float)), **`AL_VELOCITY`** (array(float,float,float)) and **`AL_ORIENTATION`** (array(float,float,float)). ### Return Values Returns a float or array of floats (as appropriate) or **`false`** on failure. ### See Also * [openal\_listener\_set()](function.openal-listener-set) - Set a listener property php imap_listscan imap\_listscan ============== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_listscan — Returns the list of mailboxes that matches the given text ### Description ``` imap_listscan( IMAP\Connection $imap, string $reference, string $pattern, string $content ): array|false ``` Returns an array containing the names of the mailboxes that have `content` in the text of the mailbox. This function is similar to [imap\_listmailbox()](function.imap-listmailbox), but it will additionally check for the presence of the string `content` inside the mailbox data. ### Parameters `imap` An [IMAP\Connection](class.imap-connection) instance. `reference` `reference` should normally be just the server specification as described in [imap\_open()](function.imap-open) **Warning** Passing untrusted data to this parameter is *insecure*, unless [imap.enable\_insecure\_rsh](https://www.php.net/manual/en/imap.configuration.php#ini.imap.enable-insecure-rsh) is disabled. `pattern` Specifies where in the mailbox hierarchy to start searching. There are two special characters you can pass as part of the `pattern`: '`*`' and '`%`'. '`*`' means to return all mailboxes. If you pass `pattern` as '`*`', you will get a list of the entire mailbox hierarchy. '`%`' means to return the current level only. '`%`' as the `pattern` parameter will return only the top level mailboxes; '`~/mail/%`' on `UW_IMAPD` will return every mailbox in the ~/mail directory, but none in subfolders of that directory. `content` The searched string ### Return Values Returns an array containing the names of the mailboxes that have `content` in the text of the mailbox, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `imap` parameter expects an [IMAP\Connection](class.imap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [imap\_listmailbox()](function.imap-listmailbox) - Alias of imap\_list * [imap\_search()](function.imap-search) - This function returns an array of messages matching the given search criteria php SplDoublyLinkedList::add SplDoublyLinkedList::add ======================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) SplDoublyLinkedList::add — Add/insert a new value at the specified index ### Description ``` public SplDoublyLinkedList::add(int $index, mixed $value): void ``` Insert the value `value` at the specified `index`, shuffling the previous value at that index (and all subsequent values) up through the list. ### Parameters `index` The index where the new value is to be inserted. `value` The new value for the `index`. ### Return Values No value is returned. ### Errors/Exceptions Throws [OutOfRangeException](class.outofrangeexception) when `index` is out of bounds or when `index` cannot be parsed as an integer.
programming_docs
php RegexIterator::__construct RegexIterator::\_\_construct ============================ (PHP 5 >= 5.2.0, PHP 7, PHP 8) RegexIterator::\_\_construct — Create a new RegexIterator ### Description public **RegexIterator::\_\_construct**( [Iterator](class.iterator) `$iterator`, string `$pattern`, int `$mode` = RegexIterator::MATCH, int `$flags` = 0, int `$pregFlags` = 0 ) Create a new [RegexIterator](class.regexiterator) which filters an [Iterator](class.iterator) using a regular expression. ### Parameters `iterator` The iterator to apply this regex filter to. `pattern` The regular expression to match. `mode` Operation mode, see [RegexIterator::setMode()](regexiterator.setmode) for a list of modes. `flags` Special flags, see [RegexIterator::setFlags()](regexiterator.setflags) for a list of available flags. `pregFlags` The regular expression flags. These flags depend on the operation mode parameter: **[RegexIterator](class.regexiterator) preg\_flags**| operation mode | available flags | | --- | --- | | RegexIterator::ALL\_MATCHES | See [preg\_match\_all()](function.preg-match-all). | | RegexIterator::GET\_MATCH | See [preg\_match()](function.preg-match). | | RegexIterator::MATCH | See [preg\_match()](function.preg-match). | | RegexIterator::REPLACE | none. | | RegexIterator::SPLIT | See [preg\_split()](function.preg-split). | ### Errors/Exceptions Throws an [InvalidArgumentException](class.invalidargumentexception) if the `pattern` argument is invalid. ### Examples **Example #1 **RegexIterator::\_\_construct()** example** Creates a new RegexIterator that filters all strings that start with 'test'. ``` <?php $arrayIterator = new ArrayIterator(array('test 1', 'another test', 'test 123')); $regexIterator = new RegexIterator($arrayIterator, '/^test/'); foreach ($regexIterator as $value) {     echo $value . "\n"; } ?> ``` The above example will output something similar to: ``` test 1 test 123 ``` ### See Also * [preg\_match()](function.preg-match) - Perform a regular expression match * [preg\_match\_all()](function.preg-match-all) - Perform a global regular expression match * [preg\_replace()](function.preg-replace) - Perform a regular expression search and replace * [preg\_split()](function.preg-split) - Split string by a regular expression php ArrayIterator::asort ArrayIterator::asort ==================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ArrayIterator::asort — Sort entries by values ### Description ``` public ArrayIterator::asort(int $flags = SORT_REGULAR): bool ``` Sorts entries by their values. > > **Note**: > > > If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. > > ### Parameters `flags` The optional second parameter `flags` may be used to modify the sorting behavior using these values: Sorting type flags: * **`SORT_REGULAR`** - compare items normally; the details are described in the [comparison operators](language.operators.comparison) section * **`SORT_NUMERIC`** - compare items numerically * **`SORT_STRING`** - compare items as strings * **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. It uses the locale, which can be changed using [setlocale()](function.setlocale) * **`SORT_NATURAL`** - compare items as strings using "natural ordering" like [natsort()](function.natsort) * **`SORT_FLAG_CASE`** - can be combined (bitwise OR) with **`SORT_STRING`** or **`SORT_NATURAL`** to sort strings case-insensitively ### Return Values Always returns **`true`**. ### See Also * [ArrayIterator::ksort()](arrayiterator.ksort) - Sort entries by keys * [ArrayIterator::natcasesort()](arrayiterator.natcasesort) - Sort entries naturally, case insensitive * [ArrayIterator::natsort()](arrayiterator.natsort) - Sort entries naturally * [ArrayIterator::uasort()](arrayiterator.uasort) - Sort with a user-defined comparison function and maintain index association * [ArrayIterator::uksort()](arrayiterator.uksort) - Sort by keys using a user-defined comparison function * [asort()](function.asort) - Sort an array in ascending order and maintain index association php enchant_dict_suggest enchant\_dict\_suggest ====================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL enchant >= 0.1.0 ) enchant\_dict\_suggest — Will return a list of values if any of those pre-conditions are not met ### Description ``` enchant_dict_suggest(EnchantDictionary $dictionary, string $word): array ``` ### Parameters `dictionary` An Enchant dictionary returned by [enchant\_broker\_request\_dict()](function.enchant-broker-request-dict) or [enchant\_broker\_request\_pwl\_dict()](function.enchant-broker-request-pwl-dict). `word` Word to use for the suggestions. ### Return Values Will returns an array of suggestions if the word is bad spelled. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dictionary` expects an [EnchantDictionary](class.enchantdictionary) instance now; previoulsy, a [resource](language.types.resource) was expected. | ### Examples **Example #1 A **enchant\_dict\_suggest()** example** ``` <?php $tag = 'en_US'; $r = enchant_broker_init(); if (enchant_broker_dict_exists($r,$tag)) {     $d = enchant_broker_request_dict($r, $tag);     $wordcorrect = enchant_dict_check($d, "soong");     if (!$wordcorrect) {         $suggs = enchant_dict_suggest($d, "soong");         echo "Suggestions for 'soong':";         print_r($suggs);     }     enchant_broker_free_dict($d); } enchant_broker_free($r); ?> ``` ### See Also * [enchant\_dict\_check()](function.enchant-dict-check) - Check whether a word is correctly spelled or not * [enchant\_dict\_quick\_check()](function.enchant-dict-quick-check) - Check the word is correctly spelled and provide suggestions php mysqli::set_opt mysqli::set\_opt ================ mysqli\_set\_opt ================ (PHP 5, PHP 7, PHP 8) mysqli::set\_opt -- mysqli\_set\_opt — Alias of [mysqli\_options()](mysqli.options) ### Description This function is an alias of: [mysqli\_options()](mysqli.options). php DOMDocument::load DOMDocument::load ================= (PHP 5, PHP 7, PHP 8) DOMDocument::load — Load XML from a file ### Description ``` public DOMDocument::load(string $filename, int $options = 0): DOMDocument|bool ``` Loads an XML document from a file. **Warning** Unix style paths with forward slashes can cause significant performance degradation on Windows systems; be sure to call [realpath()](function.realpath) in such a case. ### Parameters `filename` The path to the XML document. `options` [Bitwise `OR`](language.operators.bitwise) of the [libxml option constants](https://www.php.net/manual/en/libxml.constants.php). ### Return Values Returns **`true`** on success or **`false`** on failure. If called statically, returns a [DOMDocument](class.domdocument) or **`false`** on failure. ### Errors/Exceptions If an empty string is passed as the `filename` or an empty file is named, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions. Prior to PHP 8.0.0 this method *could* be called statically, but would issue an **`E_DEPRECATED`** error. As of PHP 8.0.0 calling this method statically throws an [Error](class.error) exception ### Examples **Example #1 Creating a Document** ``` <?php $doc = new DOMDocument(); $doc->load('book.xml'); echo $doc->saveXML(); ?> ``` ### See Also * [DOMDocument::loadXML()](domdocument.loadxml) - Load XML from a string * [DOMDocument::save()](domdocument.save) - Dumps the internal XML tree back into a file * [DOMDocument::saveXML()](domdocument.savexml) - Dumps the internal XML tree back into a string php Ds\Deque::sort Ds\Deque::sort ============== (PECL ds >= 1.0.0) Ds\Deque::sort — Sorts the deque in-place ### Description ``` public Ds\Deque::sort(callable $comparator = ?): void ``` Sorts the deque in-place, using an optional `comparator` function. ### Parameters `comparator` The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. ``` callback(mixed $a, mixed $b): int ``` **Caution** Returning *non-integer* values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ### Return Values No value is returned. ### Examples **Example #1 **Ds\Deque::sort()** example** ``` <?php $deque = new \Ds\Deque([4, 5, 1, 3, 2]); $deque->sort(); print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 ) ``` **Example #2 **Ds\Deque::sort()** example using a comparator** ``` <?php $deque = new \Ds\Deque([4, 5, 1, 3, 2]); $deque->sort(function($a, $b) {     return $b <=> $a; }); print_r($deque); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => 5 [1] => 4 [2] => 3 [3] => 2 [4] => 1 ) ``` php SolrDocument::unserialize SolrDocument::unserialize ========================= (PECL solr >= 0.9.2) SolrDocument::unserialize — Custom serialization of SolrDocument objects ### Description ``` public SolrDocument::unserialize(string $serialized): void ``` Custom serialization of SolrDocument objects ### Parameters `serialized` An XML representation of the document. ### Return Values None. php SolrQuery::setFacetDateStart SolrQuery::setFacetDateStart ============================ (PECL solr >= 0.9.2) SolrQuery::setFacetDateStart — Maps to facet.date.start ### Description ``` public SolrQuery::setFacetDateStart(string $value, string $field_override = ?): SolrQuery ``` Maps to facet.date.start ### Parameters `value` See facet.date.start `field_override` The name of the field. ### Return Values Returns the current SolrQuery object, if the return value is used. php GearmanJob::complete GearmanJob::complete ==================== (PECL gearman <= 0.5.0) GearmanJob::complete — Send the result and complete status (deprecated) ### Description ``` public GearmanJob::complete(string $result): bool ``` Sends result data and the complete status update for this job. > > **Note**: > > > This method has been replaced by [GearmanJob::sendComplete()](gearmanjob.sendcomplete) in the 0.6.0 release of the Gearman extension. > > ### Parameters `result` Serialized result data. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::sendFail()](gearmanjob.sendfail) - Send fail status * [GearmanJob::setReturn()](gearmanjob.setreturn) - Set a return value php SolrResponse::setParseMode SolrResponse::setParseMode ========================== (PECL solr >= 0.9.2) SolrResponse::setParseMode — Sets the parse mode ### Description ``` public SolrResponse::setParseMode(int $parser_mode = 0): bool ``` Sets the parse mode. ### Parameters `parser_mode` SolrResponse::PARSE\_SOLR\_DOC parses documents in SolrDocument instances. SolrResponse::PARSE\_SOLR\_OBJ parses document into SolrObjects. ### Return Values Returns **`true`** on success or **`false`** on failure. php EvLoop::loopFork EvLoop::loopFork ================ (PECL ev >= 0.2.0) EvLoop::loopFork — Must be called after a fork ### Description ``` public EvLoop::loopFork(): void ``` Must be called after a *fork* in the child, before entering or continuing the event loop. An alternative is to use **`Ev::FLAG_FORKCHECK`** which calls this function automatically, at some performance loss (refer to the [» libev documentation](http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#FUNCTIONS_CONTROLLING_EVENT_LOOPS) ). ### Parameters This function has no parameters. ### Return Values No value is returned. php ArrayObject::asort ArrayObject::asort ================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ArrayObject::asort — Sort the entries by value ### Description ``` public ArrayObject::asort(int $flags = SORT_REGULAR): bool ``` Sorts the entries in ascending order, such that its keys maintain their correlation with the values they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant. > > **Note**: > > > If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. > > ### Parameters `flags` The optional second parameter `flags` may be used to modify the sorting behavior using these values: Sorting type flags: * **`SORT_REGULAR`** - compare items normally; the details are described in the [comparison operators](language.operators.comparison) section * **`SORT_NUMERIC`** - compare items numerically * **`SORT_STRING`** - compare items as strings * **`SORT_LOCALE_STRING`** - compare items as strings, based on the current locale. It uses the locale, which can be changed using [setlocale()](function.setlocale) * **`SORT_NATURAL`** - compare items as strings using "natural ordering" like [natsort()](function.natsort) * **`SORT_FLAG_CASE`** - can be combined (bitwise OR) with **`SORT_STRING`** or **`SORT_NATURAL`** to sort strings case-insensitively ### Return Values Always returns **`true`**. ### Examples **Example #1 **ArrayObject::asort()** example** ``` <?php $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); $fruitArrayObject = new ArrayObject($fruits); $fruitArrayObject->asort(); foreach ($fruitArrayObject as $key => $val) {     echo "$key = $val\n"; } ?> ``` The above example will output: ``` c = apple b = banana d = lemon a = orange ``` The fruits have been sorted in alphabetical order, and the key associated with each entry has been maintained. ### See Also * [ArrayObject::ksort()](arrayobject.ksort) - Sort the entries by key * [ArrayObject::natsort()](arrayobject.natsort) - Sort entries using a "natural order" algorithm * [ArrayObject::natcasesort()](arrayobject.natcasesort) - Sort an array using a case insensitive "natural order" algorithm * [ArrayObject::uasort()](arrayobject.uasort) - Sort the entries with a user-defined comparison function and maintain key association * [ArrayObject::uksort()](arrayobject.uksort) - Sort the entries by keys using a user-defined comparison function * [asort()](function.asort) - Sort an array in ascending order and maintain index association php Imagick::getImageWidth Imagick::getImageWidth ====================== (PECL imagick 2, PECL imagick 3) Imagick::getImageWidth — Returns the image width ### Description ``` public Imagick::getImageWidth(): int ``` Returns the image width. ### Parameters This function has no parameters. ### Return Values Returns the image width. ### Errors/Exceptions Throws ImagickException on error. php SolrQuery::addSortField SolrQuery::addSortField ======================= (PECL solr >= 0.9.2) SolrQuery::addSortField — Used to control how the results should be sorted ### Description ``` public SolrQuery::addSortField(string $field, int $order = SolrQuery::ORDER_DESC): SolrQuery ``` Used to control how the results should be sorted. ### Parameters `field` The name of the field `order` The sort direction. This should be either SolrQuery::ORDER\_ASC or SolrQuery::ORDER\_DESC. ### Return Values Returns the current SolrQuery object. php mysqli::refresh mysqli::refresh =============== mysqli\_refresh =============== (PHP 5 >= 5.3.0, PHP 7, PHP 8) mysqli::refresh -- mysqli\_refresh — Refreshes ### Description Object-oriented style ``` public mysqli::refresh(int $flags): bool ``` Procedural style ``` mysqli_refresh(mysqli $mysql, int $flags): bool ``` Flushes tables or caches, or resets the replication server information. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `flags` The options to refresh, using the MYSQLI\_REFRESH\_\* constants as documented within the [MySQLi constants](https://www.php.net/manual/en/mysqli.constants.php) documentation. See also the official [» MySQL Refresh](http://dev.mysql.com/doc/mysql/en/mysql-refresh.html) documentation. ### Return Values **`true`** if the refresh was a success, otherwise **`false`** ### See Also * [mysqli\_poll()](mysqli.poll) - Poll connections php Ds\Deque::slice Ds\Deque::slice =============== (PECL ds >= 1.0.0) Ds\Deque::slice — Returns a sub-deque of a given range ### Description ``` public Ds\Deque::slice(int $index, int $length = ?): Ds\Deque ``` Creates a sub-deque of a given range. ### Parameters `index` The index at which the sub-deque starts. If positive, the deque will start at that index in the deque. If negative, the deque will start that far from the end. `length` If a length is given and is positive, the resulting deque will have up to that many values in it. If the length results in an overflow, only values up to the end of the deque will be included. If a length is given and is negative, the deque will stop that many values from the end. If a length is not provided, the resulting deque will contain all values between the index and the end of the deque. ### Return Values A sub-deque of the given range. ### Examples **Example #1 **Ds\Deque::slice()** example** ``` <?php $deque = new \Ds\Deque(["a", "b", "c", "d", "e"]); // Slice from 2 onwards print_r($deque->slice(2)); // Slice from 1, for a length of 3 print_r($deque->slice(1, 3)); // Slice from 1 onwards print_r($deque->slice(1)); // Slice from 2 from the end onwards print_r($deque->slice(-2)); // Slice from 1 to 1 from the end print_r($deque->slice(1, -1)); ?> ``` The above example will output something similar to: ``` Ds\Deque Object ( [0] => c [1] => d [2] => e ) Ds\Deque Object ( [0] => b [1] => c [2] => d ) Ds\Deque Object ( [0] => b [1] => c [2] => d [3] => e ) Ds\Deque Object ( [0] => d [1] => e ) Ds\Deque Object ( [0] => b [1] => c [2] => d ) ``` php Yaf_Config_Simple::__set Yaf\_Config\_Simple::\_\_set ============================ (Yaf >=1.0.0) Yaf\_Config\_Simple::\_\_set — The \_\_set purpose ### Description ``` public Yaf_Config_Simple::__set(string $name, string $value): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` `value` ### Return Values php Yaf_Route_Supervar::assemble Yaf\_Route\_Supervar::assemble ============================== (Yaf >=2.3.0) Yaf\_Route\_Supervar::assemble — Assemble a url ### Description ``` public Yaf_Route_Supervar::assemble(array $info, array $query = ?): string ``` Assemble a url. ### Parameters `info` `query` ### Return Values Returns a string. ### Errors/Exceptions Throws [Yaf\_Exception\_TypeError](class.yaf-exception-typeerror) if `info` keys `':c'` and `':a'` are not set. ### Examples **Example #1 **Yaf\_Route\_Supervar::assemble()** example** ``` <?php $router = new Yaf_Router(); $route  = new Yaf_Route_Supervar('r'); $router->addRoute("supervar", $route); var_dump($router->getRoute('supervar')->assemble(         array(               ':a' => 'yafaction',               'tkey' => 'tval',               ':c' => 'yafcontroller',               ':m' => 'yafmodule'         ),         array(               'tkey1' => 'tval1',               'tkey2' => 'tval2'         ) )); try { var_dump($router->getRoute('supervar')->assemble(         array(               ':a' => 'yafaction',               'tkey' => 'tval',               ':m' => 'yafmodule'         ),         array(               'tkey1' => 'tval1',               'tkey2' => 'tval2',               1 => array(),         ) )); } catch (Exception $e) {     var_dump($e->getMessage()); } ``` The above example will output something similar to: ``` string(%d) "?r=/yafmodule/yafcontroller/yafaction&tkey1=tval1&tkey2=tval2" string(%d) "You need to specify the controller by ':c'" ```
programming_docs
php move_uploaded_file move\_uploaded\_file ==================== (PHP 4 >= 4.0.3, PHP 5, PHP 7, PHP 8) move\_uploaded\_file — Moves an uploaded file to a new location ### Description ``` move_uploaded_file(string $from, string $to): bool ``` This function checks to ensure that the file designated by `from` is a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism). If the file is valid, it will be moved to the filename given by `to`. This sort of check is especially important if there is any chance that anything done with uploaded files could reveal their contents to the user, or even to other users on the same system. ### Parameters `from` The filename of the uploaded file. `to` The destination of the moved file. ### Return Values Returns **`true`** on success. If `from` is not a valid upload file, then no action will occur, and **move\_uploaded\_file()** will return **`false`**. If `from` is a valid upload file, but cannot be moved for some reason, no action will occur, and **move\_uploaded\_file()** will return **`false`**. Additionally, a warning will be issued. ### Examples **Example #1 Uploading multiple files** ``` <?php $uploads_dir = '/uploads'; foreach ($_FILES["pictures"]["error"] as $key => $error) {     if ($error == UPLOAD_ERR_OK) {         $tmp_name = $_FILES["pictures"]["tmp_name"][$key];         // basename() may prevent filesystem traversal attacks;         // further validation/sanitation of the filename may be appropriate         $name = basename($_FILES["pictures"]["name"][$key]);         move_uploaded_file($tmp_name, "$uploads_dir/$name");     } } ?> ``` ### Notes > > **Note**: > > > **move\_uploaded\_file()** is [open\_basedir](https://www.php.net/manual/en/ini.core.php#ini.open-basedir) aware. However, restrictions are placed only on the `to` path as to allow the moving of uploaded files in which `from` may conflict with such restrictions. **move\_uploaded\_file()** ensures the safety of this operation by allowing only those files uploaded through PHP to be moved. > > **Warning** If the destination file already exists, it will be overwritten. ### See Also * [is\_uploaded\_file()](function.is-uploaded-file) - Tells whether the file was uploaded via HTTP POST * [rename()](function.rename) - Renames a file or directory * See [Handling file uploads](https://www.php.net/manual/en/features.file-upload.php) for a simple usage example php mysqli::$client_version mysqli::$client\_version ======================== mysqli\_get\_client\_version ============================ (PHP 5, PHP 7, PHP 8) mysqli::$client\_version -- mysqli\_get\_client\_version — Returns the MySQL client version as an integer ### Description Object-oriented style int [$mysqli->client\_version](mysqli.get-client-version); Procedural style ``` mysqli_get_client_version(): int ``` Returns client version number as an integer. ### Parameters This function has no parameters. ### Return Values A number that represents the MySQL client library version in format: `main_version*10000 + minor_version *100 + sub_version`. For example, 4.1.0 is returned as 40100. This is useful to quickly determine the version of the client library to know if some capability exists. ### Examples **Example #1 mysqli\_get\_client\_version** ``` <?php /* We don't need a connection to determine    the version of mysql client library */ printf("Client library version: %d\n", mysqli_get_client_version()); ?> ``` ### See Also * [mysqli\_get\_client\_info()](mysqli.get-client-info) - Get MySQL client info * [mysqli\_get\_server\_info()](mysqli.get-server-info) - Returns the version of the MySQL server * [mysqli\_get\_server\_version()](mysqli.get-server-version) - Returns the version of the MySQL server as an integer php Parle\RParser::validate Parle\RParser::validate ======================= (PECL parle >= 0.7.0) Parle\RParser::validate — Validate input ### Description ``` public Parle\RParser::validate(string $data, Parle\RLexer $lexer): bool ``` Validate an input string. The string is parsed internally, thus this method is useful for the quick input validation. ### Parameters `data` String to be validated. `lexer` A lexer object containing the lexing rules prepared for the particular grammar. ### Return Values Returns bool whitnessing whether the input chimes or not with the defined rules. php EvStat::prev EvStat::prev ============ (PECL ev >= 0.2.0) EvStat::prev — Returns the previous set of values returned by EvStat::attr ### Description ``` public EvStat::prev(): void ``` Just like [EvStat::attr()](evstat.attr) , but returns the previous set of values. ### Parameters This function has no parameters. ### Return Values Returns an array with the same structure as the array returned by [EvStat::attr()](evstat.attr) . The array contains previously detected values. ### See Also * [EvStat::attr()](evstat.attr) - Returns the values most recently detected by Ev * [EvStat::stat()](evstat.stat) - Initiates the stat call php tidy::html tidy::html ========== tidy\_get\_html =============== (PHP 5, PHP 7, PHP 8, PECL tidy 0.5.2-1.0.0) tidy::html -- tidy\_get\_html — Returns a [tidyNode](class.tidynode) object starting from the <html> tag of the tidy parse tree ### Description Object-oriented style ``` public tidy::html(): ?tidyNode ``` Procedural style ``` tidy_get_html(tidy $tidy): ?tidyNode ``` Returns a [tidyNode](class.tidynode) object starting from the <html> tag of the tidy parse tree. ### Parameters `tidy` The [Tidy](class.tidy) object. ### Return Values Returns the [tidyNode](class.tidynode) object. ### Examples **Example #1 **tidy::html()** example** ``` <?php $html = ' <html>   <head>     <title>test</title>   </head>   <body>     <p>paragraph</p>   </body> </html>'; $tidy = tidy_parse_string($html); $html = $tidy->html(); echo $html->value; ?> ``` The above example will output: ``` <html> <head> <title>test</title> </head> <body> <p>paragraph</p> </body> </html> ``` ### See Also * [tidy::body()](tidy.body) - Returns a tidyNode object starting from the <body> tag of the tidy parse tree * [tidy::head()](tidy.head) - Returns a tidyNode object starting from the <head> tag of the tidy parse tree php sodium_crypto_box_seal_open sodium\_crypto\_box\_seal\_open =============================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_box\_seal\_open — Anonymous public-key decryption ### Description ``` sodium_crypto_box_seal_open(string $ciphertext, string $key_pair): string|false ``` Decrypt a message that was encrypted with [sodium\_crypto\_box\_seal()](function.sodium-crypto-box-seal) ### Parameters `ciphertext` The encrypted message `key_pair` The keypair of the recipient. Must include the secret key. ### Return Values The plaintext on success, or **`false`** on failure. ### Examples **Example #1 **sodium\_crypto\_box\_seal\_open()** example** ``` <?php // Ciphertext is not sensitive; base64_decode is fine $sealed_b64 = "oRBXXAV4iQBrxlV4A21Bord8Yo/D8ZlrIIGNyaRCcGBfpz0map52I3xq6l+CST+1NSgQkbV+HiYyFjXWiWiaCGupGf+zl4bgWj/A9Adtem7Jt3h3emrMsLw="; $sealed = base64_decode($sealed_b64); // Keypair contains a cryptographic secret; use a timing-safe decoder $keypair_b64 = "KZkF8wnB7bnC2aXB3lFOqCTc0Z6MllvaQb9ASVG8o2/MsewkuE4u1uaEgTzSakeiYyIW8DGj+02/L3cWIbs9bQ=="; $keypair = sodium_base642bin($keypair_b64, SODIUM_BASE64_VARIANT_ORIGINAL); $opened = sodium_crypto_box_seal_open($sealed, $keypair); var_dump($opened); ?> ``` The above example will output something similar to: ``` string(41) "Writing software in PHP can be a delight!" ``` php str_word_count str\_word\_count ================ (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) str\_word\_count — Return information about words used in a string ### Description ``` str_word_count(string $string, int $format = 0, ?string $characters = null): array|int ``` Counts the number of words inside `string`. If the optional `format` is not specified, then the return value will be an integer representing the number of words found. In the event the `format` is specified, the return value will be an array, content of which is dependent on the `format`. The possible value for the `format` and the resultant outputs are listed below. For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with "'" and "-" characters. Note that multibyte locales are not supported. ### Parameters `string` The string `format` Specify the return value of this function. The current supported values are: * 0 - returns the number of words found * 1 - returns an array containing all the words found inside the `string` * 2 - returns an associative array, where the key is the numeric position of the word inside the `string` and the value is the actual word itself `characters` A list of additional characters which will be considered as 'word' ### Return Values Returns an array or an integer, depending on the `format` chosen. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `characters` is nullable now. | ### Examples **Example #1 A **str\_word\_count()** example** ``` <?php $str = "Hello fri3nd, you're        looking          good today!"; print_r(str_word_count($str, 1)); print_r(str_word_count($str, 2)); print_r(str_word_count($str, 1, 'àáãç3')); echo str_word_count($str); ?> ``` The above example will output: ``` Array ( [0] => Hello [1] => fri [2] => nd [3] => you're [4] => looking [5] => good [6] => today ) Array ( [0] => Hello [6] => fri [10] => nd [14] => you're [29] => looking [46] => good [51] => today ) Array ( [0] => Hello [1] => fri3nd [2] => you're [3] => looking [4] => good [5] => today ) 7 ``` ### See Also * [explode()](function.explode) - Split a string by a string * [preg\_split()](function.preg-split) - Split string by a regular expression * [count\_chars()](function.count-chars) - Return information about characters used in a string * [substr\_count()](function.substr-count) - Count the number of substring occurrences php MessageFormatter::create MessageFormatter::create ======================== MessageFormatter::\_\_construct =============================== msgfmt\_create ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) MessageFormatter::create -- MessageFormatter::\_\_construct -- msgfmt\_create — Constructs a new Message Formatter ### Description Object-oriented style (method) ``` public static MessageFormatter::create(string $locale, string $pattern): ?MessageFormatter ``` Object-oriented style (constructor): public **MessageFormatter::\_\_construct**(string `$locale`, string `$pattern`) Procedural style ``` msgfmt_create(string $locale, string $pattern): ?MessageFormatter ``` Constructs a new Message Formatter ### Parameters `locale` The locale to use when formatting arguments `pattern` The pattern string to stick arguments into. The pattern uses an 'apostrophe-friendly' syntax; see [» Quoting/Escaping](https://unicode-org.github.io/icu/userguide/format_parse/messages/#quotingescaping) for details. ### Return Values The formatter object, or **`null`** on failure. ### Errors/Exceptions When invoked as constructor, on failure an [IntlException](class.intlexception) is thrown. ### Examples **Example #1 **msgfmt\_create()** example** ``` <?php $fmt = msgfmt_create("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree"); echo msgfmt_format($fmt, array(4560, 123, 4560/123)); $fmt = msgfmt_create("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum"); echo msgfmt_format($fmt, array(4560, 123, 4560/123)); ?> ``` **Example #2 OO example** ``` <?php $fmt = new MessageFormatter("en_US", "{0,number,integer} monkeys on {1,number,integer} trees make {2,number} monkeys per tree"); echo $fmt->format(array(4560, 123, 4560/123)); $fmt = new MessageFormatter("de", "{0,number,integer} Affen auf {1,number,integer} Bäumen sind {2,number} Affen pro Baum"); echo $fmt->format(array(4560, 123, 4560/123)); ?> ``` The above example will output: ``` 4,560 monkeys on 123 trees make 37.073 monkeys per tree 4.560 Affen auf 123 Bäumen sind 37,073 Affen pro Baum ``` ### See Also * [msgfmt\_format()](messageformatter.format) - Format the message * [msgfmt\_parse()](messageformatter.parse) - Parse input string according to pattern * [msgfmt\_get\_error\_code()](messageformatter.geterrorcode) - Get the error code from last operation * [msgfmt\_get\_error\_message()](messageformatter.geterrormessage) - Get the error text from the last operation php DOMChildNode::before DOMChildNode::before ==================== (PHP 8) DOMChildNode::before — Adds nodes before the node ### Description ``` public DOMChildNode::before(DOMNode|string ...$nodes): void ``` Adds the passed `nodes` before the node. ### Parameters `nodes` Nodes to be added before the node. ### Return Values No value is returned. ### See Also * [DOMChildNode::after()](domchildnode.after) - Adds nodes after the node * [DOMChildNode::remove()](domchildnode.remove) - Removes the node * [DOMChildNode::replaceWith()](domchildnode.replacewith) - Replaces the node with new nodes php Ds\Set::diff Ds\Set::diff ============ (PECL ds >= 1.0.0) Ds\Set::diff — Creates a new set using values that aren't in another set ### Description ``` public Ds\Set::diff(Ds\Set $set): Ds\Set ``` Creates a new set using values that aren't in another set. `A \ B = {x ∈ A | x ∉ B}` ### Parameters `set` Set containing the values to exclude. ### Return Values A new set containing all values that were not in the other `set`. ### See Also * [» Complement](https://en.wikipedia.org/wiki/Complement_(set_theory)) on Wikipedia ### Examples **Example #1 **Ds\Set::diff()** example** ``` <?php $a = new \Ds\Set([1, 2, 3]); $b = new \Ds\Set([3, 4, 5]); var_dump($a->diff($b)); ?> ``` The above example will output something similar to: ``` object(Ds\Set)#3 (2) { [0]=> int(1) [1]=> int(2) } ``` php Gmagick::setimagechanneldepth Gmagick::setimagechanneldepth ============================= (PECL gmagick >= Unknown) Gmagick::setimagechanneldepth — Sets the depth of a particular image channel ### Description ``` public Gmagick::setimagechanneldepth(int $channel, int $depth): Gmagick ``` Sets the depth of a particular image channel. ### Parameters `channel` One of the [Channel](https://www.php.net/manual/en/gmagick.constants.php#gmagick.constants.channel) constant (`Gmagick::CHANNEL_*`). `depth` The image depth in bits. ### Return Values The [Gmagick](class.gmagick) object. ### Errors/Exceptions Throws an **GmagickException** on error. php XMLWriter::endElement XMLWriter::endElement ===================== xmlwriter\_end\_element ======================= (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::endElement -- xmlwriter\_end\_element — End current element ### Description Object-oriented style ``` public XMLWriter::endElement(): bool ``` Procedural style ``` xmlwriter_end_element(XMLWriter $writer): bool ``` Ends the current element. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::startElement()](xmlwriter.startelement) - Create start element tag * [XMLWriter::writeElement()](xmlwriter.writeelement) - Write full element tag php UConverter::getSubstChars UConverter::getSubstChars ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::getSubstChars — Get substitution chars ### Description ``` public UConverter::getSubstChars(): string|false|null ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Locale::getDisplayVariant Locale::getDisplayVariant ========================= locale\_get\_display\_variant ============================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Locale::getDisplayVariant -- locale\_get\_display\_variant — Returns an appropriately localized display name for variants of the input locale ### Description Object-oriented style ``` public static Locale::getDisplayVariant(string $locale, ?string $displayLocale = null): string|false ``` Procedural style ``` locale_get_display_variant(string $locale, ?string $displayLocale = null): string|false ``` Returns an appropriately localized display name for variants of the input locale. If is **`null`** then the default locale is used. ### Parameters `locale` The locale to return a display variant for `displayLocale` Optional format locale to use to display the variant name ### Return Values Display name of the variant for the `locale` in the format appropriate for `displayLocale`, or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `displayLocale` is nullable now. | ### Examples **Example #1 **locale\_get\_display\_variant()** example** ``` <?php echo locale_get_display_variant('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo locale_get_display_variant('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo locale_get_display_variant('sl-Latn-IT-nedis', 'de'); ?> ``` **Example #2 OO example** ``` <?php echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'en'); echo ";\n"; echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'fr'); echo ";\n"; echo Locale::getDisplayVariant('sl-Latn-IT-nedis', 'de'); ?> ``` The above example will output: ``` Natisone dialect; dialecte de Natisone; NEDIS ``` ### See Also * [locale\_get\_display\_name()](locale.getdisplayname) - Returns an appropriately localized display name for the input locale * [locale\_get\_display\_language()](locale.getdisplaylanguage) - Returns an appropriately localized display name for language of the inputlocale * [locale\_get\_display\_script()](locale.getdisplayscript) - Returns an appropriately localized display name for script of the input locale * [locale\_get\_display\_region()](locale.getdisplayregion) - Returns an appropriately localized display name for region of the input locale php Gmagick::getimagerenderingintent Gmagick::getimagerenderingintent ================================ (PECL gmagick >= Unknown) Gmagick::getimagerenderingintent — Gets the image rendering intent ### Description ``` public Gmagick::getimagerenderingintent(): int ``` Gets the image rendering intent ### Parameters This function has no parameters. ### Return Values Extracts a region of the image and returns it as a new wand ### Errors/Exceptions Throws an **GmagickException** on error.
programming_docs
php ReflectionClassConstant::getModifiers ReflectionClassConstant::getModifiers ===================================== (PHP 7 >= 7.1.0, PHP 8) ReflectionClassConstant::getModifiers — Gets the class constant modifiers ### Description ``` public ReflectionClassConstant::getModifiers(): int ``` Returns a bitfield of the access modifiers for this class constant. ### Parameters This function has no parameters. ### Return Values A numeric representation of the modifiers. The actual meaning of these modifiers are described under [predefined constants](class.reflectionclassconstant#reflectionclassconstant.constants.modifiers). ### See Also * [Reflection::getModifierNames()](reflection.getmodifiernames) - Gets modifier names php XMLReader::setSchema XMLReader::setSchema ==================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) XMLReader::setSchema — Validate document against XSD ### Description ``` public XMLReader::setSchema(?string $filename): bool ``` Use W3C XSD schema to validate the document as it is processed. Activation is only possible before the first Read(). ### Parameters `filename` The filename of the XSD schema. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Issues **`E_WARNING`** if libxml was built without schema support, the schema contains errors or if [XMLReader::read()](xmlreader.read) has already been called. ### Notes **Caution**This function is only available when PHP is compiled against libxml 20620 or later. ### See Also * [XMLReader::setRelaxNGSchema()](xmlreader.setrelaxngschema) - Set the filename or URI for a RelaxNG Schema * [XMLReader::setRelaxNGSchemaSource()](xmlreader.setrelaxngschemasource) - Set the data containing a RelaxNG Schema * [XMLReader::isValid()](xmlreader.isvalid) - Indicates if the parsed document is valid php fbird_drop_db fbird\_drop\_db =============== (PHP 5, PHP 7 < 7.4.0) fbird\_drop\_db — Alias of [ibase\_drop\_db()](function.ibase-drop-db) ### Description This function is an alias of: [ibase\_drop\_db()](function.ibase-drop-db). ### See Also * [fbird\_connect()](function.fbird-connect) - Alias of ibase\_connect * [fbird\_pconnect()](function.fbird-pconnect) - Alias of ibase\_pconnect php imagesy imagesy ======= (PHP 4, PHP 5, PHP 7, PHP 8) imagesy — Get image height ### Description ``` imagesy(GdImage $image): int ``` Returns the height of the given `image` object. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). ### Return Values Return the height of the `image` or **`false`** on errors. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Using **imagesy()**** ``` <?php // create a 300*200 image $img = imagecreatetruecolor(300, 200); echo imagesy($img); // 200 ?> ``` ### See Also * [imagecreatetruecolor()](function.imagecreatetruecolor) - Create a new true color image * [getimagesize()](function.getimagesize) - Get the size of an image * [imagesx()](function.imagesx) - Get image width php Errors Errors ====== Table of Contents ----------------- * [Basics](language.errors.basics) * [Errors in PHP 7](language.errors.php7) Introduction ------------ Sadly, no matter how careful we are when writing our code, errors are a fact of life. PHP will report errors, warnings and notices for many common coding and runtime problems, and knowing how to detect and handle these errors will make debugging much easier. php mcrypt_enc_get_algorithms_name mcrypt\_enc\_get\_algorithms\_name ================================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_enc\_get\_algorithms\_name — Returns the name of the opened algorithm **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_enc_get_algorithms_name(resource $td): string ``` This function returns the name of the algorithm. ### Parameters `td` The encryption descriptor. ### Return Values Returns the name of the opened algorithm as a string. ### Examples **Example #1 **mcrypt\_enc\_get\_algorithms\_name()** example** ``` <?php $td = mcrypt_module_open(MCRYPT_CAST_256, '', MCRYPT_MODE_CFB, ''); echo mcrypt_enc_get_algorithms_name($td). "\n"; $td = mcrypt_module_open('cast-256', '', MCRYPT_MODE_CFB, ''); echo mcrypt_enc_get_algorithms_name($td). "\n"; ?> ``` The above example will output: ``` CAST-256 CAST-256 ``` php EventBuffer::addBuffer EventBuffer::addBuffer ====================== (PECL event >= 1.2.6-beta) EventBuffer::addBuffer — Move all data from a buffer provided to the current instance of EventBuffer ### Description ``` public EventBuffer::addBuffer( EventBuffer $buf ): bool ``` Move all data from the buffer provided in `buf` parameter to the end of current [EventBuffer](class.eventbuffer) . This is a destructive add. The data from one buffer moves into the other buffer. However, no unnecessary memory copies occur. ### Parameters `buf` The source EventBuffer object. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventBuffer::add()](eventbuffer.add) - Append data to the end of an event buffer php Imagick::spliceImage Imagick::spliceImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::spliceImage — Splices a solid color into the image ### Description ``` public Imagick::spliceImage( int $width, int $height, int $x, int $y ): bool ``` Splices a solid color into the image. ### Parameters `width` `height` `x` `y` ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::spliceImage()**** ``` <?php function spliceImage($imagePath, $startX, $startY, $width, $height) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->spliceImage($width, $height, $startX, $startY);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php stream_get_meta_data stream\_get\_meta\_data ======================= (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) stream\_get\_meta\_data — Retrieves header/meta data from streams/file pointers ### Description ``` stream_get_meta_data(resource $stream): array ``` Returns information about an existing `stream`. ### Parameters `stream` The stream can be any stream created by [fopen()](function.fopen), [fsockopen()](function.fsockopen) [pfsockopen()](function.pfsockopen) and [stream\_socket\_client()](function.stream-socket-client). ### Return Values The result array contains the following items: * `timed_out` (bool) - **`true`** if the stream timed out while waiting for data on the last call to [fread()](function.fread) or [fgets()](function.fgets). * `blocked` (bool) - **`true`** if the stream is in blocking IO mode. See [stream\_set\_blocking()](function.stream-set-blocking). * `eof` (bool) - **`true`** if the stream has reached end-of-file. Note that for socket streams this member can be **`true`** even when `unread_bytes` is non-zero. To determine if there is more data to be read, use [feof()](function.feof) instead of reading this item. * `unread_bytes` (int) - the number of bytes currently contained in the PHP's own internal buffer. > **Note**: You shouldn't use this value in a script. > > * `stream_type` (string) - a label describing the underlying implementation of the stream. * `wrapper_type` (string) - a label describing the protocol wrapper implementation layered over the stream. See [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for more information about wrappers. * `wrapper_data` (mixed) - wrapper specific data attached to this stream. See [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) for more information about wrappers and their wrapper data. * `mode` (string) - the type of access required for this stream (see Table 1 of the [fopen()](function.fopen) reference) * `seekable` (bool) - whether the current stream can be seeked. * `uri` (string) - the URI/filename associated with this stream. * `crypto` (array) - the TLS connection metadata for this stream. (Note: Only provided when the resource's stream uses TLS.) ### Examples **Example #1 **stream\_get\_meta\_data()** example using [fopen()](function.fopen) with http** ``` <?php $url = 'http://www.example.com/'; if (!$fp = fopen($url, 'r')) {     trigger_error("Unable to open URL ($url)", E_USER_ERROR); } $meta = stream_get_meta_data($fp); var_dump($meta); fclose($fp); ?> ``` The above example will output something similar to: ``` array(10) { 'timed_out' => bool(false) 'blocked' => bool(true) 'eof' => bool(false) 'wrapper_data' => array(13) { [0] => string(15) "HTTP/1.1 200 OK" [1] => string(11) "Age: 244629" [2] => string(29) "Cache-Control: max-age=604800" [3] => string(38) "Content-Type: text/html; charset=UTF-8" [4] => string(35) "Date: Sat, 20 Nov 2021 18:17:57 GMT" [5] => string(24) "Etag: "3147526947+ident"" [6] => string(38) "Expires: Sat, 27 Nov 2021 18:17:57 GMT" [7] => string(44) "Last-Modified: Thu, 17 Oct 2019 07:18:26 GMT" [8] => string(22) "Server: ECS (chb/0286)" [9] => string(21) "Vary: Accept-Encoding" [10] => string(12) "X-Cache: HIT" [11] => string(20) "Content-Length: 1256" [12] => string(17) "Connection: close" } 'wrapper_type' => string(4) "http" 'stream_type' => string(14) "tcp_socket/ssl" 'mode' => string(1) "r" 'unread_bytes' => int(1256) 'seekable' => bool(false) 'uri' => string(23) "http://www.example.com/" } ``` **Example #2 **stream\_get\_meta\_data()** example using [stream\_socket\_client()](function.stream-socket-client) with https** ``` <?php $streamContext = stream_context_create(     [         'ssl' => [             'capture_peer_cert' => true,             'capture_peer_cert_chain' => true,             'disable_compression' => true,         ],     ] ); $client = stream_socket_client(     'ssl://www.example.com:443',     $errorNumber,     $errorDescription,     40,     STREAM_CLIENT_CONNECT,     $streamContext ); $meta = stream_get_meta_data($client); var_dump($meta); ?> ``` The above example will output something similar to: ``` array(8) { 'crypto' => array(4) { 'protocol' => string(7) "TLSv1.3" 'cipher_name' => string(22) "TLS_AES_256_GCM_SHA384" 'cipher_bits' => int(256) 'cipher_version' => string(7) "TLSv1.3" } 'timed_out' => bool(false) 'blocked' => bool(true) 'eof' => bool(false) 'stream_type' => string(14) "tcp_socket/ssl" 'mode' => string(2) "r+" 'unread_bytes' => int(0) 'seekable' => bool(false) } ``` ### Notes > > **Note**: > > > This function does NOT work on sockets created by the [Socket extension](https://www.php.net/manual/en/ref.sockets.php). > > ### See Also * [get\_headers()](function.get-headers) - Fetches all the headers sent by the server in response to an HTTP request * [$http\_response\_header](reserved.variables.httpresponseheader) php The RecursiveIterator interface The RecursiveIterator interface =============================== Introduction ------------ (PHP 5 >= 5.1.0, PHP 7, PHP 8) Classes implementing **RecursiveIterator** can be used to iterate over iterators recursively. Interface synopsis ------------------ interface **RecursiveIterator** extends [Iterator](class.iterator) { /\* Methods \*/ ``` public getChildren(): ?RecursiveIterator ``` ``` public hasChildren(): bool ``` /\* Inherited methods \*/ ``` public Iterator::current(): mixed ``` ``` public Iterator::key(): mixed ``` ``` public Iterator::next(): void ``` ``` public Iterator::rewind(): void ``` ``` public Iterator::valid(): bool ``` } Table of Contents ----------------- * [RecursiveIterator::getChildren](recursiveiterator.getchildren) — Returns an iterator for the current entry * [RecursiveIterator::hasChildren](recursiveiterator.haschildren) — Returns if an iterator can be created for the current entry php DirectoryIterator::getSize DirectoryIterator::getSize ========================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::getSize — Get size of current DirectoryIterator item ### Description ``` public DirectoryIterator::getSize(): int ``` Get the file size for the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values Returns the size of the file, in bytes. ### Examples **Example #1 **DirectoryIterator::getSize()** example** ``` <?php $iterator = new DirectoryIterator(dirname(__FILE__)); foreach ($iterator as $fileinfo) {     if ($fileinfo->isFile()) {         echo $fileinfo->getFilename() . " " . $fileinfo->getSize() . "\n";     } } ?> ``` The above example will output something similar to: ``` apple.jpg 15385 banana.jpg 15190 example.php 170 pear.jpg 34406 ``` ### See Also * [filesize()](function.filesize) - Gets file size php radius_demangle radius\_demangle ================ (PECL radius >= 1.2.0) radius\_demangle — Demangles data ### Description ``` radius_demangle(resource $radius_handle, string $mangled): string ``` Some data (Passwords, MS-CHAPv1 MPPE-Keys) is mangled for security reasons, and must be demangled before you can use them. ### Parameters `radius_handle` The RADIUS resource. `mangled` The mangled data to demangle ### Return Values Returns the demangled string, or **`false`** on error. php imagestringup imagestringup ============= (PHP 4, PHP 5, PHP 7, PHP 8) imagestringup — Draw a string vertically ### Description ``` imagestringup( GdImage $image, GdFont|int $font, int $x, int $y, string $string, int $color ): bool ``` Draws a `string` vertically at the given coordinates. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `font` Can be 1, 2, 3, 4, 5 for built-in fonts in latin2 encoding (where higher numbers corresponding to larger fonts) or [GdFont](class.gdfont) instance, returned by [imageloadfont()](function.imageloadfont). `x` x-coordinate of the bottom left corner. `y` y-coordinate of the bottom left corner. `string` The string to be written. `color` A color identifier created with [imagecolorallocate()](function.imagecolorallocate). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `font` parameter now accepts both an [GdFont](class.gdfont) instance and an int; previously only int was accepted. | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 **imagestringup()** example** ``` <?php // create a 100*100 image $im = imagecreatetruecolor(100, 100); // Write the text $textcolor = imagecolorallocate($im, 0xFF, 0xFF, 0xFF); imagestringup($im, 3, 40, 80, 'gd library', $textcolor); // Save the image imagepng($im, './stringup.png'); imagedestroy($im); ?> ``` The above example will output something similar to: ### See Also * [imagestring()](function.imagestring) - Draw a string horizontally * [imageloadfont()](function.imageloadfont) - Load a new font php IntlChar::isULowercase IntlChar::isULowercase ====================== (PHP 7, PHP 8) IntlChar::isULowercase — Check if code point has the Lowercase Unicode property ### Description ``` public static IntlChar::isULowercase(int|string $codepoint): ?bool ``` Check if a code point has the Lowercase Unicode property. This is the same as `IntlChar::hasBinaryProperty($codepoint, IntlChar::PROPERTY_LOWERCASE)` > > **Note**: > > > This is different than [IntlChar::islower()](intlchar.islower) and will return **`true`** for more characters. > > ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` has the Lowercase Unicode property, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isULowercase("A")); var_dump(IntlChar::isULowercase("a")); var_dump(IntlChar::isULowercase("Φ")); var_dump(IntlChar::isULowercase("φ")); var_dump(IntlChar::isULowercase("1")); ?> ``` The above example will output: ``` bool(false) bool(true) bool(false) bool(true) bool(false) ``` ### See Also * [IntlChar::islower()](intlchar.islower) - Check if code point is a lowercase letter * [IntlChar::hasBinaryProperty()](intlchar.hasbinaryproperty) - Check a binary Unicode property for a code point * **`IntlChar::PROPERTY_LOWERCASE`** php ReflectionClass::getInterfaces ReflectionClass::getInterfaces ============================== (PHP 5, PHP 7, PHP 8) ReflectionClass::getInterfaces — Gets the interfaces ### Description ``` public ReflectionClass::getInterfaces(): array ``` Gets the interfaces. ### Parameters This function has no parameters. ### Return Values An associative array of interfaces, with keys as interface names and the array values as [ReflectionClass](class.reflectionclass) objects. ### Examples **Example #1 **ReflectionClass::getInterfaces()** example** ``` <?php interface Foo { } interface Bar { } class Baz implements Foo, Bar { } $rc1 = new ReflectionClass("Baz"); print_r($rc1->getInterfaces()); ?> ``` The above example will output something similar to: ``` Array ( [Foo] => ReflectionClass Object ( [name] => Foo ) [Bar] => ReflectionClass Object ( [name] => Bar ) ) ``` ### See Also * [ReflectionClass::getInterfaceNames()](reflectionclass.getinterfacenames) - Gets the interface names php EventListener::disable EventListener::disable ====================== (PECL event >= 1.2.6-beta) EventListener::disable — Disables an event connect listener object ### Description ``` public EventListener::disable(): bool ``` Disables an event connect listener object ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [EventListener::enable()](eventlistener.enable) - Enables an event connect listener object php The Iterator interface The Iterator interface ====================== Introduction ------------ (PHP 5, PHP 7, PHP 8) Interface for external iterators or objects that can be iterated themselves internally. Interface synopsis ------------------ interface **Iterator** extends [Traversable](class.traversable) { /\* Methods \*/ ``` public current(): mixed ``` ``` public key(): mixed ``` ``` public next(): void ``` ``` public rewind(): void ``` ``` public valid(): bool ``` } Predefined iterators -------------------- PHP already provides a number of iterators for many day to day tasks. See [SPL iterators](https://www.php.net/manual/en/spl.iterators.php) for a list. Examples -------- **Example #1 Basic usage** This example demonstrates in which order methods are called when using [foreach](control-structures.foreach) with an iterator. ``` <?php class myIterator implements Iterator {     private $position = 0;     private $array = array(         "firstelement",         "secondelement",         "lastelement",     );       public function __construct() {         $this->position = 0;     }     public function rewind(): void {         var_dump(__METHOD__);         $this->position = 0;     }     #[ReturnTypeWillChange]     public function current() {         var_dump(__METHOD__);         return $this->array[$this->position];     }     #[ReturnTypeWillChange]     public function key() {         var_dump(__METHOD__);         return $this->position;     }     public function next(): void {         var_dump(__METHOD__);         ++$this->position;     }     public function valid(): bool {         var_dump(__METHOD__);         return isset($this->array[$this->position]);     } } $it = new myIterator; foreach($it as $key => $value) {     var_dump($key, $value);     echo "\n"; } ?> ``` The above example will output something similar to: ``` string(18) "myIterator::rewind" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(0) string(12) "firstelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(1) string(13) "secondelement" string(16) "myIterator::next" string(17) "myIterator::valid" string(19) "myIterator::current" string(15) "myIterator::key" int(2) string(11) "lastelement" string(16) "myIterator::next" string(17) "myIterator::valid" ``` See Also -------- See also [object iteration](language.oop5.iterations). Table of Contents ----------------- * [Iterator::current](iterator.current) — Return the current element * [Iterator::key](iterator.key) — Return the key of the current element * [Iterator::next](iterator.next) — Move forward to next element * [Iterator::rewind](iterator.rewind) — Rewind the Iterator to the first element * [Iterator::valid](iterator.valid) — Checks if current position is valid
programming_docs
php Imagick::sketchImage Imagick::sketchImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::sketchImage — Simulates a pencil sketch ### Description ``` public Imagick::sketchImage(float $radius, float $sigma, float $angle): bool ``` Simulates a pencil sketch. We convolve the image with a Gaussian operator of the given radius and standard deviation (sigma). For reasonable results, radius should be larger than sigma. Use a radius of 0 and Imagick::sketchImage() selects a suitable radius for you. Angle gives the angle of the blurring motion. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `radius` The radius of the Gaussian, in pixels, not counting the center pixel `sigma` The standard deviation of the Gaussian, in pixels. `angle` Apply the effect along this angle. ### Return Values Returns **`true`** on success. ### Examples **Example #1 **Imagick::sketchImage()**** ``` <?php function sketchImage($imagePath, $radius, $sigma, $angle) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->sketchimage($radius, $sigma, $angle);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php Memcached::prependByKey Memcached::prependByKey ======================= (PECL memcached >= 0.1.0) Memcached::prependByKey — Prepend data to an existing item on a specific server ### Description ``` public Memcached::prependByKey(string $server_key, string $key, string $value): bool ``` **Memcached::prependByKey()** is functionally equivalent to [Memcached::prepend()](memcached.prepend), except that the free-form `server_key` can be used to map the `key` to a specific server. ### Parameters `server_key` The key identifying the server to store the value on or retrieve it from. Instead of hashing on the actual key for the item, we hash on the server key when deciding which memcached server to talk to. This allows related items to be grouped together on a single server for efficiency with multi operations. `key` The key of the item to prepend the data to. `value` The string to prepend. ### Return Values Returns **`true`** on success or **`false`** on failure. The [Memcached::getResultCode()](memcached.getresultcode) will return **`Memcached::RES_NOTSTORED`** if the key does not exist. ### See Also * [Memcached::prepend()](memcached.prepend) - Prepend data to an existing item * [Memcached::append()](memcached.append) - Append data to an existing item php Ds\Deque::join Ds\Deque::join ============== (PECL ds >= 1.0.0) Ds\Deque::join — Joins all values together as a string ### Description ``` public Ds\Deque::join(string $glue = ?): string ``` Joins all values together as a string using an optional separator between each value. ### Parameters `glue` An optional string to separate each value. ### Return Values All values of the deque joined together as a string. ### Examples **Example #1 **Ds\Deque::join()** example using a separator string** ``` <?php $deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]); var_dump($deque->join("|")); ?> ``` The above example will output something similar to: ``` string(11) "a|b|c|1|2|3" ``` **Example #2 **Ds\Deque::join()** example without a separator string** ``` <?php $deque = new \Ds\Deque(["a", "b", "c", 1, 2, 3]); var_dump($deque->join()); ?> ``` The above example will output something similar to: ``` string(11) "abc123" ``` php mysqli_stmt::bind_param mysqli\_stmt::bind\_param ========================= mysqli\_stmt\_bind\_param ========================= (PHP 5, PHP 7, PHP 8) mysqli\_stmt::bind\_param -- mysqli\_stmt\_bind\_param — Binds variables to a prepared statement as parameters ### Description Object-oriented style ``` public mysqli_stmt::bind_param(string $types, mixed &$var, mixed &...$vars): bool ``` Procedural style ``` mysqli_stmt_bind_param( mysqli_stmt $statement, string $types, mixed &$var, mixed &...$vars ): bool ``` Bind variables for the parameter markers in the SQL statement prepared by [mysqli\_prepare()](mysqli.prepare) or [mysqli\_stmt\_prepare()](mysqli-stmt.prepare). > > **Note**: > > > If data size of a variable exceeds max. allowed packet size (max\_allowed\_packet), you have to specify `b` in `types` and use [mysqli\_stmt\_send\_long\_data()](mysqli-stmt.send-long-data) to send the data in packets. > > > > **Note**: > > > Care must be taken when using **mysqli\_stmt\_bind\_param()** in conjunction with [call\_user\_func\_array()](function.call-user-func-array). Note that **mysqli\_stmt\_bind\_param()** requires parameters to be passed by reference, whereas [call\_user\_func\_array()](function.call-user-func-array) can accept as a parameter a list of variables that can represent references or values. > > ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). `types` A string that contains one or more characters which specify the types for the corresponding bind variables: **Type specification chars**| Character | Description | | --- | --- | | i | corresponding variable has type int | | d | corresponding variable has type float | | s | corresponding variable has type string | | b | corresponding variable is a blob and will be sent in packets | `var` `vars` The number of variables and length of string `types` must match the parameters in the statement. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **mysqli\_stmt::bind\_param()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); $stmt = $mysqli->prepare("INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); $stmt->bind_param('sssd', $code, $language, $official, $percent); $code = 'DEU'; $language = 'Bavarian'; $official = "F"; $percent = 11.2; $stmt->execute(); printf("%d row inserted.\n", $stmt->affected_rows); /* Clean up table CountryLanguage */ $mysqli->query("DELETE FROM CountryLanguage WHERE Language='Bavarian'"); printf("%d row deleted.\n", $mysqli->affected_rows); ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect('localhost', 'my_user', 'my_password', 'world'); $stmt = mysqli_prepare($link, "INSERT INTO CountryLanguage VALUES (?, ?, ?, ?)"); mysqli_stmt_bind_param($stmt, 'sssd', $code, $language, $official, $percent); $code = 'DEU'; $language = 'Bavarian'; $official = "F"; $percent = 11.2; mysqli_stmt_execute($stmt); printf("%d row inserted.\n", mysqli_stmt_affected_rows($stmt)); /* Clean up table CountryLanguage */ mysqli_query($link, "DELETE FROM CountryLanguage WHERE Language='Bavarian'"); printf("%d row deleted.\n", mysqli_affected_rows($link)); ``` The above examples will output: ``` 1 row inserted. 1 row deleted. ``` **Example #2 Using `...` to provide arguments** The `...` operator can be used to provide variable-length argument list, e.g. in a `WHERE IN` clause. ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world'); $stmt = $mysqli->prepare("SELECT Language FROM CountryLanguage WHERE CountryCode IN (?, ?)"); /* Using ... to provide arguments */ $stmt->bind_param('ss', ...['DEU', 'POL']); $stmt->execute(); $stmt->store_result(); printf("%d rows found.\n", $stmt->num_rows()); ``` The above examples will output: ``` 10 rows found. ``` ### See Also * [mysqli\_stmt\_bind\_result()](mysqli-stmt.bind-result) - Binds variables to a prepared statement for result storage * [mysqli\_stmt\_execute()](mysqli-stmt.execute) - Executes a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_send\_long\_data()](mysqli-stmt.send-long-data) - Send data in blocks * [mysqli\_stmt\_errno()](mysqli-stmt.errno) - Returns the error code for the most recent statement call * [mysqli\_stmt\_error()](mysqli-stmt.error) - Returns a string description for last statement error php ArrayObject::getFlags ArrayObject::getFlags ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) ArrayObject::getFlags — Gets the behavior flags ### Description ``` public ArrayObject::getFlags(): int ``` Gets the behavior flags of the [ArrayObject](class.arrayobject). See the [ArrayObject::setFlags](arrayobject.setflags) method for a list of the available flags. ### Parameters This function has no parameters. ### Return Values Returns the behavior flags of the ArrayObject. ### Examples **Example #1 **ArrayObject::getFlags()** example** ``` <?php // Array of available fruits $fruits = array("lemons" => 1, "oranges" => 4, "bananas" => 5, "apples" => 10); $fruitsArrayObject = new ArrayObject($fruits); // Get the current flags $flags = $fruitsArrayObject->getFlags(); var_dump($flags); // Set new flags $fruitsArrayObject->setFlags(ArrayObject::ARRAY_AS_PROPS); // Get the new flags $flags = $fruitsArrayObject->getFlags(); var_dump($flags); ?> ``` The above example will output: ``` int(0) int(2) ``` ### See Also * [ArrayObject::setFlags()](arrayobject.setflags) - Sets the behavior flags php Ds\Deque::__construct Ds\Deque::\_\_construct ======================= (PECL ds >= 1.0.0) Ds\Deque::\_\_construct — Creates a new instance ### Description public **Ds\Deque::\_\_construct**([mixed](language.types.declarations#language.types.declarations.mixed) `$values` = ?) Creates a new instance, using either a [traversable](class.traversable) object or an array for the initial `values`. ### Parameters `values` A traversable object or an array to use for the initial values. ### Examples **Example #1 **Ds\Deque::\_\_construct()** example** ``` <?php $deque = new \Ds\Deque(); var_dump($deque); $deque = new \Ds\Deque([1, 2, 3]); var_dump($deque); ?> ``` The above example will output something similar to: ``` object(Ds\Deque)#2 (0) { } object(Ds\Deque)#2 (3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } ``` php SoapServer::addSoapHeader SoapServer::addSoapHeader ========================= (PHP 5 >= 5.1.3, PHP 7, PHP 8) SoapServer::addSoapHeader — Add a SOAP header to the response ### Description ``` public SoapServer::addSoapHeader(SoapHeader $header): void ``` Adds a SOAP header to be returned with the response to the current request. ### Parameters `header` The header to be returned. ### Return Values No value is returned. php DOMElement::setAttributeNS DOMElement::setAttributeNS ========================== (PHP 5, PHP 7, PHP 8) DOMElement::setAttributeNS — Adds new attribute ### Description ``` public DOMElement::setAttributeNS(?string $namespace, string $qualifiedName, string $value): void ``` Sets an attribute with namespace `namespace` and name `name` to the given value. If the attribute does not exist, it will be created. ### Parameters `namespace` The namespace URI. `qualifiedName` The qualified name of the attribute, as `prefix:tagname`. `value` The value of the attribute. ### Return Values No value is returned. ### Errors/Exceptions **`DOM_NO_MODIFICATION_ALLOWED_ERR`** Raised if the node is readonly. **`DOM_NAMESPACE_ERR`** Raised if `qualifiedName` is a malformed qualified name, or if `qualifiedName` has a prefix and `namespace` is **`null`**. ### See Also * [DOMElement::hasAttributeNS()](domelement.hasattributens) - Checks to see if attribute exists * [DOMElement::getAttributeNS()](domelement.getattributens) - Returns value of attribute * [DOMElement::removeAttributeNS()](domelement.removeattributens) - Removes attribute php socket_wsaprotocol_info_import socket\_wsaprotocol\_info\_import ================================= (PHP 7 >= 7.3.0, PHP 8) socket\_wsaprotocol\_info\_import — Imports a Socket from another Process ### Description ``` socket_wsaprotocol_info_import(string $info_id): Socket|false ``` Imports a socket which has formerly been exported from another process. > **Note**: This function is available only on Windows. > > ### Parameters `info_id` The ID which has been returned by a former call to [socket\_wsaprotocol\_info\_export()](function.socket-wsaprotocol-info-export). ### Return Values Returns a [Socket](class.socket) instance on success, or **`false`** on failure ### Changelog | Version | Description | | --- | --- | | 8.0.0 | On success, this function returns a [Socket](class.socket) instance now; previously, a resource was returned. | ### See Also * [socket\_wsaprotocol\_info\_export()](function.socket-wsaprotocol-info-export) - Exports the WSAPROTOCOL\_INFO Structure php Yaf_Controller_Abstract::getInvokeArgs Yaf\_Controller\_Abstract::getInvokeArgs ======================================== (Yaf >=1.0.0) Yaf\_Controller\_Abstract::getInvokeArgs — The getInvokeArgs purpose ### Description ``` public Yaf_Controller_Abstract::getInvokeArgs(): void ``` ### Parameters This function has no parameters. ### Return Values php Parle\RLexer::push Parle\RLexer::push ================== (PECL parle >= 0.5.1) Parle\RLexer::push — Add a lexer rule ### Description ``` public Parle\RLexer::push(string $regex, int $id): void ``` ``` public Parle\RLexer::push( string $state, string $regex, int $id, string $newState ): void ``` ``` public Parle\RLexer::push(string $state, string $regex, string $newState): void ``` Push a pattern for lexeme recognition. A 'start state' and 'exit state' can be specified by using a suitable signature. ### Parameters `regex` Regular expression used for token matching. `id` Token id. If the lexer instance is meant to be used standalone, this can be an arbitrary number. If the lexer instance is going to be passed to the parser, it has to be an id returned by [Parle\RParser::tokenid()](parle-rparser.tokenid). `state` State name. If '\*' is used as start state, then the rule is applied to all lexer states. `newState` New state name, after the rule was applied. If '.' is specified as the exit state, then the lexer state is unchanged when that rule matches. An exit state with '>' before the name means push. Use the signature without id for either continuation or to start matching, when a continuation or recursion is required. If '<' is specified as exit state, it means pop. In that case, the signature containing the id can be used to identify the match. Note that even in the case an id is specified, the rule will finish first when all the previous pushes popped. ### Return Values No value is returned. php sscanf sscanf ====== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) sscanf — Parses input from a string according to a format ### Description ``` sscanf(string $string, string $format, mixed &...$vars): array|int|null ``` The function **sscanf()** is the input analog of [printf()](function.printf). **sscanf()** reads from the string `string` and interprets it according to the specified `format`. Any whitespace in the format string matches any whitespace in the input string. This means that even a tab (`\t`) in the format string can match a single space character in the input string. ### Parameters `string` The input string being parsed. `format` The interpreted format for `string`, which is described in the documentation for [sprintf()](function.sprintf) with following differences: * Function is not locale-aware. * `F`, `g`, `G` and `b` are not supported. * `D` stands for decimal number. * `i` stands for integer with base detection. * `n` stands for number of characters processed so far. * `s` stops reading at any whitespace character. * `*` instead of `argnum$` suppresses the assignment of this conversion specification. `vars` Optionally pass in variables by reference that will contain the parsed values. ### Return Values If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference. If there are more substrings expected in the `format` than there are available within `string`, **`null`** will be returned. ### Examples **Example #1 **sscanf()** Example** ``` <?php // getting the serial number list($serial) = sscanf("SN/2350001", "SN/%d"); // and the date of manufacturing $mandate = "January 01 2000"; list($month, $day, $year) = sscanf($mandate, "%s %d %d"); echo "Item $serial was manufactured on: $year-" . substr($month, 0, 3) . "-$day\n"; ?> ``` If optional parameters are passed, the function will return the number of assigned values. **Example #2 **sscanf()** - using optional parameters** ``` <?php // get author info and generate DocBook entry $auth = "24\tLewis Carroll"; $n = sscanf($auth, "%d\t%s %s", $id, $first, $last); echo "<author id='$id'>     <firstname>$first</firstname>     <surname>$last</surname> </author>\n"; ?> ``` ### See Also * [printf()](function.printf) - Output a formatted string * [sprintf()](function.sprintf) - Return a formatted string * [fprintf()](function.fprintf) - Write a formatted string to a stream * [vprintf()](function.vprintf) - Output a formatted string * [vsprintf()](function.vsprintf) - Return a formatted string * [vfprintf()](function.vfprintf) - Write a formatted string to a stream * [fscanf()](function.fscanf) - Parses input from a file according to a format * [number\_format()](function.number-format) - Format a number with grouped thousands * [date()](function.date) - Format a Unix timestamp php DirectoryIterator::__construct DirectoryIterator::\_\_construct ================================ (PHP 5, PHP 7, PHP 8) DirectoryIterator::\_\_construct — Constructs a new directory iterator from a path ### Description public **DirectoryIterator::\_\_construct**(string `$directory`) Constructs a new directory iterator from a path. ### Parameters `directory` The path of the directory to traverse. ### Errors/Exceptions Throws an [UnexpectedValueException](class.unexpectedvalueexception) if the `directory` does not exist. Throws a [ValueError](class.valueerror) if the `directory` is an empty string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Now throws a [ValueError](class.valueerror) if `directory` is an empty string; previously it threw a [RuntimeException](class.runtimeexception). | ### Examples **Example #1 A **DirectoryIterator::\_\_construct()** example** This example will list the contents of the directory containing the script. ``` <?php $dir = new DirectoryIterator(dirname(__FILE__)); foreach ($dir as $fileinfo) {     if (!$fileinfo->isDot()) {         var_dump($fileinfo->getFilename());     } } ?> ``` ### See Also * [SplFileInfo](class.splfileinfo) * [Iterator](class.iterator) php The ReflectionMethod class The ReflectionMethod class ========================== Introduction ------------ (PHP 5, PHP 7, PHP 8) The **ReflectionMethod** class reports information about a method. Class synopsis -------------- class **ReflectionMethod** extends [ReflectionFunctionAbstract](class.reflectionfunctionabstract) { /\* Constants \*/ public const int [IS\_STATIC](class.reflectionmethod#reflectionmethod.constants.is-static); public const int [IS\_PUBLIC](class.reflectionmethod#reflectionmethod.constants.is-public); public const int [IS\_PROTECTED](class.reflectionmethod#reflectionmethod.constants.is-protected); public const int [IS\_PRIVATE](class.reflectionmethod#reflectionmethod.constants.is-private); public const int [IS\_ABSTRACT](class.reflectionmethod#reflectionmethod.constants.is-abstract); public const int [IS\_FINAL](class.reflectionmethod#reflectionmethod.constants.is-final); /\* Properties \*/ public string [$class](class.reflectionmethod#reflectionmethod.props.class); /\* Inherited properties \*/ public string [$name](class.reflectionfunctionabstract#reflectionfunctionabstract.props.name); /\* Methods \*/ public [\_\_construct](reflectionmethod.construct)(object|string `$objectOrMethod`, string `$method`) public [\_\_construct](reflectionmethod.construct)(string `$classMethod`) ``` public static export(string $class, string $name, bool $return = false): string ``` ``` public getClosure(?object $object = null): Closure ``` ``` public getDeclaringClass(): ReflectionClass ``` ``` public getModifiers(): int ``` ``` public getPrototype(): ReflectionMethod ``` ``` public hasPrototype(): bool ``` ``` public invoke(?object $object, mixed ...$args): mixed ``` ``` public invokeArgs(?object $object, array $args): mixed ``` ``` public isAbstract(): bool ``` ``` public isConstructor(): bool ``` ``` public isDestructor(): bool ``` ``` public isFinal(): bool ``` ``` public isPrivate(): bool ``` ``` public isProtected(): bool ``` ``` public isPublic(): bool ``` ``` public isStatic(): bool ``` ``` public setAccessible(bool $accessible): void ``` ``` public __toString(): string ``` /\* Inherited methods \*/ ``` private ReflectionFunctionAbstract::__clone(): void ``` ``` public ReflectionFunctionAbstract::getAttributes(?string $name = null, int $flags = 0): array ``` ``` public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass ``` ``` public ReflectionFunctionAbstract::getClosureThis(): ?object ``` ``` public ReflectionFunctionAbstract::getClosureUsedVariables(): array ``` ``` public ReflectionFunctionAbstract::getDocComment(): string|false ``` ``` public ReflectionFunctionAbstract::getEndLine(): int|false ``` ``` public ReflectionFunctionAbstract::getExtension(): ?ReflectionExtension ``` ``` public ReflectionFunctionAbstract::getExtensionName(): string|false ``` ``` public ReflectionFunctionAbstract::getFileName(): string|false ``` ``` public ReflectionFunctionAbstract::getName(): string ``` ``` public ReflectionFunctionAbstract::getNamespaceName(): string ``` ``` public ReflectionFunctionAbstract::getNumberOfParameters(): int ``` ``` public ReflectionFunctionAbstract::getNumberOfRequiredParameters(): int ``` ``` public ReflectionFunctionAbstract::getParameters(): array ``` ``` public ReflectionFunctionAbstract::getReturnType(): ?ReflectionType ``` ``` public ReflectionFunctionAbstract::getShortName(): string ``` ``` public ReflectionFunctionAbstract::getStartLine(): int|false ``` ``` public ReflectionFunctionAbstract::getStaticVariables(): array ``` ``` public ReflectionFunctionAbstract::getTentativeReturnType(): ?ReflectionType ``` ``` public ReflectionFunctionAbstract::hasReturnType(): bool ``` ``` public ReflectionFunctionAbstract::hasTentativeReturnType(): bool ``` ``` public ReflectionFunctionAbstract::inNamespace(): bool ``` ``` public ReflectionFunctionAbstract::isClosure(): bool ``` ``` public ReflectionFunctionAbstract::isDeprecated(): bool ``` ``` public ReflectionFunctionAbstract::isGenerator(): bool ``` ``` public ReflectionFunctionAbstract::isInternal(): bool ``` ``` public ReflectionFunctionAbstract::isUserDefined(): bool ``` ``` public ReflectionFunctionAbstract::isVariadic(): bool ``` ``` public ReflectionFunctionAbstract::returnsReference(): bool ``` ``` abstract public ReflectionFunctionAbstract::__toString(): void ``` } Properties ---------- name Method name class Class name Predefined Constants -------------------- ReflectionMethod Modifiers -------------------------- **`ReflectionMethod::IS_STATIC`** Indicates that the method is static. Prior to PHP 7.4.0, the value was `1`. **`ReflectionMethod::IS_PUBLIC`** Indicates that the method is public. Prior to PHP 7.4.0, the value was `256`. **`ReflectionMethod::IS_PROTECTED`** Indicates that the method is protected. Prior to PHP 7.4.0, the value was `512`. **`ReflectionMethod::IS_PRIVATE`** Indicates that the method is private. Prior to PHP 7.4.0, the value was `1024`. **`ReflectionMethod::IS_ABSTRACT`** Indicates that the method is abstract. Prior to PHP 7.4.0, the value was `2`. **`ReflectionMethod::IS_FINAL`** Indicates that the method is final. Prior to PHP 7.4.0, the value was `4`. > > **Note**: > > > The values of these constants may change between PHP versions. It is recommended to always use the constants and not rely on the values directly. > > Table of Contents ----------------- * [ReflectionMethod::\_\_construct](reflectionmethod.construct) — Constructs a ReflectionMethod * [ReflectionMethod::export](reflectionmethod.export) — Export a reflection method * [ReflectionMethod::getClosure](reflectionmethod.getclosure) — Returns a dynamically created closure for the method * [ReflectionMethod::getDeclaringClass](reflectionmethod.getdeclaringclass) — Gets declaring class for the reflected method * [ReflectionMethod::getModifiers](reflectionmethod.getmodifiers) — Gets the method modifiers * [ReflectionMethod::getPrototype](reflectionmethod.getprototype) — Gets the method prototype (if there is one) * [ReflectionMethod::hasPrototype](reflectionmethod.hasprototype) — Returns whether a method has a prototype * [ReflectionMethod::invoke](reflectionmethod.invoke) — Invoke * [ReflectionMethod::invokeArgs](reflectionmethod.invokeargs) — Invoke args * [ReflectionMethod::isAbstract](reflectionmethod.isabstract) — Checks if method is abstract * [ReflectionMethod::isConstructor](reflectionmethod.isconstructor) — Checks if method is a constructor * [ReflectionMethod::isDestructor](reflectionmethod.isdestructor) — Checks if method is a destructor * [ReflectionMethod::isFinal](reflectionmethod.isfinal) — Checks if method is final * [ReflectionMethod::isPrivate](reflectionmethod.isprivate) — Checks if method is private * [ReflectionMethod::isProtected](reflectionmethod.isprotected) — Checks if method is protected * [ReflectionMethod::isPublic](reflectionmethod.ispublic) — Checks if method is public * [ReflectionMethod::isStatic](reflectionmethod.isstatic) — Checks if method is static * [ReflectionMethod::setAccessible](reflectionmethod.setaccessible) — Set method accessibility * [ReflectionMethod::\_\_toString](reflectionmethod.tostring) — Returns the string representation of the Reflection method object
programming_docs
php RecursiveTreeIterator::current RecursiveTreeIterator::current ============================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::current — Get current element ### Description ``` public RecursiveTreeIterator::current(): mixed ``` Gets the current element prefixed and postfixed. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns the current element prefixed and postfixed. php glob glob ==== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) glob — Find pathnames matching a pattern ### Description ``` glob(string $pattern, int $flags = 0): array|false ``` The **glob()** function searches for all the pathnames matching `pattern` according to the rules used by the libc glob() function, which is similar to the rules used by common shells. ### Parameters `pattern` The pattern. No tilde expansion or parameter substitution is done. Special characters: * `*` - Matches zero or more characters. * `?` - Matches exactly one character (any character). * `[...]` - Matches one character from a group of characters. If the first character is `!`, matches any character not in the group. * `\` - Escapes the following character, except when the **`GLOB_NOESCAPE`** flag is used. `flags` Valid flags: * **`GLOB_MARK`** - Adds a slash (a backslash on Windows) to each directory returned * **`GLOB_NOSORT`** - Return files as they appear in the directory (no sorting). When this flag is not used, the pathnames are sorted alphabetically * **`GLOB_NOCHECK`** - Return the search pattern if no files matching it were found * **`GLOB_NOESCAPE`** - Backslashes do not quote metacharacters * **`GLOB_BRACE`** - Expands {a,b,c} to match 'a', 'b', or 'c' * **`GLOB_ONLYDIR`** - Return only directory entries which match the pattern * **`GLOB_ERR`** - Stop on read errors (like unreadable directories), by default errors are ignored. > **Note**: The **`GLOB_BRACE`** flag is not available on some non GNU systems, like Solaris or Alpine Linux. > > ### Return Values Returns an array containing the matched files/directories, an empty array if no file matched or **`false`** on error. > > **Note**: > > > On some systems it is impossible to distinguish between empty match and an error. > > ### Examples **Example #1 Convenient way how **glob()** can replace [opendir()](function.opendir) and friends.** ``` <?php foreach (glob("*.txt") as $filename) {     echo "$filename size " . filesize($filename) . "\n"; } ?> ``` The above example will output something similar to: ``` funclist.txt size 44686 funcsummary.txt size 267625 quickref.txt size 137820 ``` ### Notes > **Note**: This function will not work on [remote files](https://www.php.net/manual/en/features.remote-files.php) as the file to be examined must be accessible via the server's filesystem. > > > **Note**: This function isn't available on some systems (e.g. old Sun OS). > > ### See Also * [opendir()](function.opendir) - Open directory handle * [readdir()](function.readdir) - Read entry from directory handle * [closedir()](function.closedir) - Close directory handle * [fnmatch()](function.fnmatch) - Match filename against a pattern php uopz_unset_return uopz\_unset\_return =================== (PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_unset\_return — Unsets a previously set return value for a function ### Description ``` uopz_unset_return(string $function): bool ``` ``` uopz_unset_return(string $class, string $function): bool ``` Unsets the return value of the `function` previously set by [uopz\_set\_return()](function.uopz-set-return). ### Parameters `class` The name of the class containing the function `function` The name of the function ### Return Values True on success ### Examples **Example #1 **uopz\_unset\_return()** example** ``` <?php uopz_set_return("strlen", 42); $len = strlen("Banana"); uopz_unset_return("strlen"); echo $len + strlen("Banana"); ?> ``` The above example will output: ``` 48 ``` php mb_decode_mimeheader mb\_decode\_mimeheader ====================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) mb\_decode\_mimeheader — Decode string in MIME header field ### Description ``` mb_decode_mimeheader(string $string): string ``` Decodes encoded-word string `string` in MIME header. ### Parameters `string` The string being decoded. ### Return Values The decoded string in internal character encoding. ### See Also * [mb\_encode\_mimeheader()](function.mb-encode-mimeheader) - Encode string for MIME header php ReflectionClass::isInstance ReflectionClass::isInstance =========================== (PHP 5, PHP 7, PHP 8) ReflectionClass::isInstance — Checks class for instance ### Description ``` public ReflectionClass::isInstance(object $object): bool ``` Checks if an object is an instance of a class. ### Parameters `object` The object being compared to. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **ReflectionClass::isInstance()** related examples** ``` <?php // Example usage $class = new ReflectionClass('Foo'); if ($class->isInstance($arg)) {     echo "Yes"; } // Equivalent to if ($arg instanceof Foo) {     echo "Yes"; } // Equivalent to if (is_a($arg, 'Foo')) {     echo "Yes"; } ?> ``` The above example will output something similar to: ``` Yes Yes Yes ``` ### See Also * [ReflectionClass::isInterface()](reflectionclass.isinterface) - Checks if the class is an interface * [Type operators (instanceof)](language.operators.type) * [Object Interfaces](language.oop5.interfaces) * [is\_a()](function.is-a) - Checks if the object is of this object type or has this object type as one of its parents php EvLoop::child EvLoop::child ============= (PECL ev >= 0.2.0) EvLoop::child — Creates EvChild object associated with the current event loop ### Description ``` final public EvLoop::child( string $pid , string $trace , string $callback , string $data = ?, string $priority = ? ): EvChild ``` Creates EvChild object associated with the current event loop. ### Parameters All parameters have the same meaning as for [EvChild::\_\_construct()](evchild.construct) ### Return Values Returns EvChild object on success. ### See Also * [EvChild::\_\_construct()](evchild.construct) - Constructs the EvChild watcher object php DOMDocument::loadXML DOMDocument::loadXML ==================== (PHP 5, PHP 7, PHP 8) DOMDocument::loadXML — Load XML from a string ### Description ``` public DOMDocument::loadXML(string $source, int $options = 0): DOMDocument|bool ``` Loads an XML document from a string. ### Parameters `source` The string containing the XML. `options` [Bitwise `OR`](language.operators.bitwise) of the [libxml option constants](https://www.php.net/manual/en/libxml.constants.php). ### Return Values Returns **`true`** on success or **`false`** on failure. If called statically, returns a [DOMDocument](class.domdocument) or **`false`** on failure. ### Errors/Exceptions If an empty string is passed as the `source`, a warning will be generated. This warning is not generated by libxml and cannot be handled using libxml's error handling functions. Prior to PHP 8.0.0 this method *could* be called statically, but would issue an **`E_DEPRECATED`** error. As of PHP 8.0.0 calling this method statically throws an [Error](class.error) exception ### Examples **Example #1 Creating a Document** ``` <?php $doc = new DOMDocument(); $doc->loadXML('<root><node/></root>'); echo $doc->saveXML(); ?> ``` **Example #2 Static invocation of `loadXML`** ``` <?php // Issues an E_DEPRECATED error $doc = DOMDocument::loadXML('<root><node/></root>'); echo $doc->saveXML(); ?> ``` ### See Also * [DOMDocument::load()](domdocument.load) - Load XML from a file * [DOMDocument::save()](domdocument.save) - Dumps the internal XML tree back into a file * [DOMDocument::saveXML()](domdocument.savexml) - Dumps the internal XML tree back into a string php SplDoublyLinkedList::next SplDoublyLinkedList::next ========================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplDoublyLinkedList::next — Move to next entry ### Description ``` public SplDoublyLinkedList::next(): void ``` Move the iterator to the next node. ### Parameters This function has no parameters. ### Return Values No value is returned. php debug_zval_dump debug\_zval\_dump ================= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) debug\_zval\_dump — Dumps a string representation of an internal zval structure to output ### Description ``` debug_zval_dump(mixed $value, mixed ...$values): void ``` Dumps a string representation of an internal zval (Zend value) structure to output. This is mostly useful for understanding or debugging implementation details of the Zend Engine or PHP extensions. ### Parameters `value` The variable or value to dump. `values` Further variables or values to dump. ### Return Values No value is returned. ### Examples **Example #1 **debug\_zval\_dump()** example** ``` <?php $var1 = 'Hello'; $var1 .= ' World'; $var2 = $var1; debug_zval_dump($var1); ?> ``` The above example will output: ``` string(11) "Hello World" refcount(3) ``` > > **Note**: **Understanding the `refcount`** > > > > The `refcount` value shown by this function may be surprising without a detailed understanding of the engine's implementation. > > The Zend Engine uses reference counting for two different purposes: > > > * Optimizing memory usage using a technique called "copy on write", where multiple variables holding the same value point to the same copy in memory. When any of the variables is modified, it is pointed to a new copy in memory, and the reference count on the original is decreased by 1. > * Tracking variables which have been assigned or passed by reference (see [References Explained](https://www.php.net/manual/en/language.references.php)). This refcount is stored on a separate reference zval, pointing to the zval for the current value. This additional zval is not currently shown by **debug\_zval\_dump()**. > > Because **debug\_zval\_dump()** takes its input as normal parameters, passed by value, the copy on write technique will be used to pass them: rather than copying the data, the refcount will be increased by one for the lifetime of the function call. If the function modified the parameter after receiving it, then a copy would be made; since it does not, it will show a refcount one higher than in the calling scope. > > The parameter passing also prevents **debug\_zval\_dump()** showing variables which have been assigned by reference. To illustrate, consider a slightly modified version of the above example: > > > > ``` > <?php > $var1 = 'Hello'; > $var1 .= ' World'; > // Point three variables as references to the same value > $var2 =& $var1; > $var3 =& $var1; > > debug_zval_dump($var1); > ?> > ``` > The above example will output: > > > ``` > > string(11) "Hello World" refcount(2) > > ``` > Although $var1, $var2, and $var3 are linked as references, only the *value* is passed to **debug\_zval\_dump()**. That value is used once by the set of references, and once inside the **debug\_zval\_dump()**, so shows a refcount of 2. > > Further complications arise because of optimisations made in the engine for different data types. Some types such as integers do not use "copy on write", so do not show a refcount at all. In other cases, the refcount shows extra copies used internally, such as when a literal string or array is stored as part of a code instruction. > > ### See Also * [var\_dump()](function.var-dump) - Dumps information about a variable * [debug\_backtrace()](function.debug-backtrace) - Generates a backtrace * [References Explained](https://www.php.net/manual/en/language.references.php) * [» References Explained (by Derick Rethans)](http://derickrethans.nl/php_references_article.php) php sapi_windows_generate_ctrl_event sapi\_windows\_generate\_ctrl\_event ==================================== (PHP 7 >= 7.4.0, PHP 8) sapi\_windows\_generate\_ctrl\_event — Send a CTRL event to another process ### Description ``` sapi_windows_generate_ctrl_event(int $event, int $pid = 0): bool ``` Sends a CTRL event to another process in the same process group. ### Parameters `event` The `CTRL` even to send; either **`PHP_WINDOWS_EVENT_CTRL_C`** or **`PHP_WINDOWS_EVENT_CTRL_BREAK`**. `pid` The ID of the process to which to send the event to. If `0` is given, the event is sent to all processes of the process group. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Basic **sapi\_windows\_generate\_ctrl\_event()** Usage** This example shows how to pass along `CTRL+BREAK` events to a child process. In this case the child process echoes `I'm still alive` every second, until the user presses `CTRL+BREAK`, what causes only the child process to be terminated. ``` <?php // forward CTRL+BREAK events to the child process sapi_windows_set_ctrl_handler('sapi_windows_generate_ctrl_event'); // create a child process which echoes every second $cmd = ['php', '-r', 'while (true) { echo "I\'m still alive\n"; sleep(1); }']; $descspec = array(['pipe', 'r'], ['pipe', 'w'], ['pipe', 'w']); $options = ['create_process_group' => true]; $proc = proc_open($cmd, $descspec, $pipes, null, null, $options); while (true) {     echo fgets($pipes[1]); } ?> ``` ### See Also * [proc\_open()](function.proc-open) - Execute a command and open file pointers for input/output * [sapi\_windows\_set\_ctrl\_handler()](function.sapi-windows-set-ctrl-handler) - Set or remove a CTRL event handler php show_source show\_source ============ (PHP 4, PHP 5, PHP 7, PHP 8) show\_source — Alias of [highlight\_file()](function.highlight-file) ### Description This function is an alias of: [highlight\_file()](function.highlight-file). php Imagick::evaluateImage Imagick::evaluateImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::evaluateImage — Applies an expression to an image ### Description ``` public Imagick::evaluateImage(int $op, float $constant, int $channel = Imagick::CHANNEL_DEFAULT): bool ``` Applys an arithmetic, relational, or logical expression to an image. Use these operators to lighten or darken an image, to increase or decrease contrast in an image, or to produce the "negative" of an image. ### Parameters `op` The evaluation operator `constant` The value of the operator `channel` Provide any channel constant that is valid for your channel mode. To apply to more than one channel, combine channeltype constants using bitwise operators. Refer to this list of [channel constants](https://www.php.net/manual/en/imagick.constants.php#imagick.constants.channel). ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 Using **Imagick::evaluateImage()**** Using evaluateImage to reduce opacity in an image. ``` <?php // Create new object with the image $im = new Imagick('example-alpha.png'); // Reduce the alpha by 50% $im->evaluateImage(Imagick::EVALUATE_DIVIDE, 2, Imagick::CHANNEL_ALPHA); // Output the image header("Content-Type: image/png"); echo $im; ?> ``` php The GlobIterator class The GlobIterator class ====================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) Iterates through a file system in a similar fashion to [glob()](function.glob). Class synopsis -------------- class **GlobIterator** extends [FilesystemIterator](class.filesystemiterator) implements [Countable](class.countable) { /\* Inherited constants \*/ public const int [FilesystemIterator::CURRENT\_MODE\_MASK](class.filesystemiterator#filesystemiterator.constants.current-mode-mask); public const int [FilesystemIterator::CURRENT\_AS\_PATHNAME](class.filesystemiterator#filesystemiterator.constants.current-as-pathname); public const int [FilesystemIterator::CURRENT\_AS\_FILEINFO](class.filesystemiterator#filesystemiterator.constants.current-as-fileinfo); public const int [FilesystemIterator::CURRENT\_AS\_SELF](class.filesystemiterator#filesystemiterator.constants.current-as-self); public const int [FilesystemIterator::KEY\_MODE\_MASK](class.filesystemiterator#filesystemiterator.constants.key-mode-mask); public const int [FilesystemIterator::KEY\_AS\_PATHNAME](class.filesystemiterator#filesystemiterator.constants.key-as-pathname); public const int [FilesystemIterator::FOLLOW\_SYMLINKS](class.filesystemiterator#filesystemiterator.constants.follow-symlinks); public const int [FilesystemIterator::KEY\_AS\_FILENAME](class.filesystemiterator#filesystemiterator.constants.key-as-filename); public const int [FilesystemIterator::NEW\_CURRENT\_AND\_KEY](class.filesystemiterator#filesystemiterator.constants.new-current-and-key); public const int [FilesystemIterator::OTHER\_MODE\_MASK](class.filesystemiterator#filesystemiterator.constants.other-mode-mask); public const int [FilesystemIterator::SKIP\_DOTS](class.filesystemiterator#filesystemiterator.constants.skip-dots); public const int [FilesystemIterator::UNIX\_PATHS](class.filesystemiterator#filesystemiterator.constants.unix-paths); /\* Methods \*/ public [\_\_construct](globiterator.construct)(string `$pattern`, int `$flags` = FilesystemIterator::KEY\_AS\_PATHNAME | FilesystemIterator::CURRENT\_AS\_FILEINFO) ``` public count(): int ``` /\* Inherited methods \*/ ``` public FilesystemIterator::current(): string|SplFileInfo|FilesystemIterator ``` ``` public FilesystemIterator::getFlags(): int ``` ``` public FilesystemIterator::key(): string ``` ``` public FilesystemIterator::next(): void ``` ``` public FilesystemIterator::rewind(): void ``` ``` public FilesystemIterator::setFlags(int $flags): void ``` ``` public DirectoryIterator::current(): mixed ``` ``` public DirectoryIterator::getATime(): int ``` ``` public DirectoryIterator::getBasename(string $suffix = ""): string ``` ``` public DirectoryIterator::getCTime(): int ``` ``` public DirectoryIterator::getExtension(): string ``` ``` public DirectoryIterator::getFilename(): string ``` ``` public DirectoryIterator::getGroup(): int ``` ``` public DirectoryIterator::getInode(): int ``` ``` public DirectoryIterator::getMTime(): int ``` ``` public DirectoryIterator::getOwner(): int ``` ``` public DirectoryIterator::getPath(): string ``` ``` public DirectoryIterator::getPathname(): string ``` ``` public DirectoryIterator::getPerms(): int ``` ``` public DirectoryIterator::getSize(): int ``` ``` public DirectoryIterator::getType(): string ``` ``` public DirectoryIterator::isDir(): bool ``` ``` public DirectoryIterator::isDot(): bool ``` ``` public DirectoryIterator::isExecutable(): bool ``` ``` public DirectoryIterator::isFile(): bool ``` ``` public DirectoryIterator::isLink(): bool ``` ``` public DirectoryIterator::isReadable(): bool ``` ``` public DirectoryIterator::isWritable(): bool ``` ``` public DirectoryIterator::key(): mixed ``` ``` public DirectoryIterator::next(): void ``` ``` public DirectoryIterator::rewind(): void ``` ``` public DirectoryIterator::seek(int $offset): void ``` ``` public DirectoryIterator::__toString(): string ``` ``` public DirectoryIterator::valid(): bool ``` ``` public SplFileInfo::getATime(): int|false ``` ``` public SplFileInfo::getBasename(string $suffix = ""): string ``` ``` public SplFileInfo::getCTime(): int|false ``` ``` public SplFileInfo::getExtension(): string ``` ``` public SplFileInfo::getFileInfo(?string $class = null): SplFileInfo ``` ``` public SplFileInfo::getFilename(): string ``` ``` public SplFileInfo::getGroup(): int|false ``` ``` public SplFileInfo::getInode(): int|false ``` ``` public SplFileInfo::getLinkTarget(): string|false ``` ``` public SplFileInfo::getMTime(): int|false ``` ``` public SplFileInfo::getOwner(): int|false ``` ``` public SplFileInfo::getPath(): string ``` ``` public SplFileInfo::getPathInfo(?string $class = null): ?SplFileInfo ``` ``` public SplFileInfo::getPathname(): string ``` ``` public SplFileInfo::getPerms(): int|false ``` ``` public SplFileInfo::getRealPath(): string|false ``` ``` public SplFileInfo::getSize(): int|false ``` ``` public SplFileInfo::getType(): string|false ``` ``` public SplFileInfo::isDir(): bool ``` ``` public SplFileInfo::isExecutable(): bool ``` ``` public SplFileInfo::isFile(): bool ``` ``` public SplFileInfo::isLink(): bool ``` ``` public SplFileInfo::isReadable(): bool ``` ``` public SplFileInfo::isWritable(): bool ``` ``` public SplFileInfo::openFile(string $mode = "r", bool $useIncludePath = false, ?resource $context = null): SplFileObject ``` ``` public SplFileInfo::setFileClass(string $class = SplFileObject::class): void ``` ``` public SplFileInfo::setInfoClass(string $class = SplFileInfo::class): void ``` ``` public SplFileInfo::__toString(): string ``` } Table of Contents ----------------- * [GlobIterator::\_\_construct](globiterator.construct) — Construct a directory using glob * [GlobIterator::count](globiterator.count) — Get the number of directories and files
programming_docs
php SolrQuery::getTermsIncludeLowerBound SolrQuery::getTermsIncludeLowerBound ==================================== (PECL solr >= 0.9.2) SolrQuery::getTermsIncludeLowerBound — Returns whether or not to include the lower bound in the result set ### Description ``` public SolrQuery::getTermsIncludeLowerBound(): bool ``` Returns whether or not to include the lower bound in the result set ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php min min === (PHP 4, PHP 5, PHP 7, PHP 8) min — Find lowest value ### Description ``` min(mixed $value, mixed ...$values): mixed ``` Alternative signature (not supported with named arguments): ``` min(array $value_array): mixed ``` If the first and only parameter is an array, **min()** returns the lowest value in that array. If at least two parameters are provided, **min()** returns the smallest of these values. > > **Note**: > > > Values of different types will be compared using the [standard comparison rules](language.operators.comparison). For instance, a non-numeric string will be compared to an int as though it were `0`, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied. > > **Caution** Be careful when passing arguments of different types because **min()** can produce unpredictable results. ### Parameters `value` Any [comparable](language.operators.comparison) value. `values` Any [comparable](language.operators.comparison) values. `value_array` An array containing the values. ### Return Values **min()** returns the parameter value considered "lowest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. `0` and `'abc'`) the first provided to the function will be returned. ### Errors/Exceptions If an empty array is passed, **min()** throws a [ValueError](class.valueerror). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | **min()** throws a [ValueError](class.valueerror) on failure now; previously, **`false`** was returned and an **`E_WARNING`** error was emitted. | ### Examples **Example #1 Example uses of **min()**** ``` <?php echo min(2, 3, 1, 6, 7);  // 1 echo min(array(2, 4, 5)); // 2 // The string 'hello' when compared to an int is treated as 0 // Since the two values are equal, the order they are provided determines the result echo min(0, 'hello');     // 0 echo min('hello', 0);     // hello // Here we are comparing -1 < 0, so -1 is the lowest value echo min('hello', -1);    // -1 // With multiple arrays of different lengths, min returns the shortest $val = min(array(2, 2, 2), array(1, 1, 1, 1)); // array(2, 2, 2) // Multiple arrays of the same length are compared from left to right // so in our example: 2 == 2, but 4 < 5 $val = min(array(2, 4, 8), array(2, 5, 1)); // array(2, 4, 8) // If both an array and non-array are given, the array is never returned // as comparisons treat arrays as greater than any other value $val = min('string', array(2, 5, 7), 42);   // string // If one argument is NULL or a boolean, it will be compared against // other values using the rules FALSE < TRUE and NULL == FALSE regardless of the  // other types involved // In the below examples, both -10 and 10 are treated as TRUE in the comparison $val = min(-10, FALSE, 10); // FALSE $val = min(-10, NULL, 10);  // NULL // 0, on the other hand, is treated as FALSE, so is "lower than" TRUE $val = min(0, TRUE); // 0 ?> ``` ### See Also * [max()](function.max) - Find highest value * [count()](function.count) - Counts all elements in an array or in a Countable object php None Backed enumerations ------------------- By default, Enumerated Cases have no scalar equivalent. They are simply singleton objects. However, there are ample cases where an Enumerated Case needs to be able to round-trip to a database or similar datastore, so having a built-in scalar (and thus trivially serializable) equivalent defined intrinsically is useful. To define a scalar equivalent for an Enumeration, the syntax is as follows: ``` <?php enum Suit: string {     case Hearts = 'H';     case Diamonds = 'D';     case Clubs = 'C';     case Spades = 'S'; } ?> ``` A case that has a scalar equivalent is called a Backed Case, as it is "Backed" by a simpler value. An Enum that contains all Backed Cases is called a "Backed Enum." A Backed Enum may contain only Backed Cases. A Pure Enum may contain only Pure Cases. A Backed Enum may be backed by types of `int` or `string`, and a given enumeration supports only a single type at a time (that is, no union of `int|string`). If an enumeration is marked as having a scalar equivalent, then all cases must have a unique scalar equivalent defined explicitly. There are no auto-generated scalar equivalents (e.g., sequential integers). Backed cases must be unique; two backed enum cases may not have the same scalar equivalent. However, a constant may refer to a case, effectively creating an alias. See [Enumeration constants](language.enumerations.constants). Equivalent values must be literals or literal expressions. Constants and constant expressions are not supported. That is, `1 + 1` is allowed, but `1 + SOME_CONST` is not. Backed Cases have an additional read-only property, `value`, which is the value specified in the definition. ``` <?php print Suit::Clubs->value; // Prints "C" ?> ``` In order to enforce the `value` property as read-only, a variable cannot be assigned as a reference to it. That is, the following throws an error: ``` <?php $suit = Suit::Clubs; $ref = &$suit->value; // Error: Cannot acquire reference to property Suit::$value ?> ``` Backed enums implement an internal [BackedEnum](class.backedenum) interface, which exposes two additional methods: * `from(int|string): self` will take a scalar and return the corresponding Enum Case. If one is not found, it will throw a [ValueError](class.valueerror). This is mainly useful in cases where the input scalar is trusted and a missing enum value should be considered an application-stopping error. * `tryFrom(int|string): ?self` will take a scalar and return the corresponding Enum Case. If one is not found, it will return `null`. This is mainly useful in cases where the input scalar is untrusted and the caller wants to implement their own error handling or default-value logic. The `from()` and `tryFrom()` methods follow standard weak/strong typing rules. In weak typing mode, passing an integer or string is acceptable and the system will coerce the value accordingly. Passing a float will also work and be coerced. In strict typing mode, passing an integer to `from()` on a string-backed enum (or vice versa) will result in a [TypeError](class.typeerror), as will a float in all circumstances. All other parameter types will throw a TypeError in both modes. ``` <?php $record = get_stuff_from_database($id); print $record['suit']; $suit =  Suit::from($record['suit']); // Invalid data throws a ValueError: "X" is not a valid scalar value for enum "Suit" print $suit->value; $suit = Suit::tryFrom('A') ?? Suit::Spades; // Invalid data returns null, so Suit::Spades is used instead. print $suit->value; ?> ``` Manually defining a `from()` or `tryFrom()` method on a Backed Enum will result in a fatal error. php ReflectionClass::export ReflectionClass::export ======================= (PHP 5, PHP 7) ReflectionClass::export — Exports a class **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionClass::export(mixed $argument, bool $return = false): string ``` Exports a reflected class. ### Parameters `argument` The reflection to export. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values If the `return` parameter is set to **`true`**, then the export is returned as a string, otherwise **`null`** is returned. ### Examples **Example #1 Basic usage of **ReflectionClass::export()**** ``` <?php class Apple {     public $var1;     public $var2 = 'Orange';     public function type() {         return 'Apple';     } } ReflectionClass::export('Apple'); ?> ``` The above example will output something similar to: ``` Class [ <user> class Apple ] { @@ php shell code 1-8 - Constants [0] { } - Static properties [0] { } - Static methods [0] { } - Properties [2] { Property [ <default> public $var1 ] Property [ <default> public $var2 ] } - Methods [1] { Method [ <user> public method type ] { @@ php shell code 5 - 7 } } } ``` ### See Also * [ReflectionClass::getName()](reflectionclass.getname) - Gets class name * [ReflectionClass::\_\_toString()](reflectionclass.tostring) - Returns the string representation of the ReflectionClass object php strcasecmp strcasecmp ========== (PHP 4, PHP 5, PHP 7, PHP 8) strcasecmp — Binary safe case-insensitive string comparison ### Description ``` strcasecmp(string $string1, string $string2): int ``` Binary safe case-insensitive string comparison. The comparison is not locale aware; only ASCII letters are compared in a case-insensitive way. ### Parameters `string1` The first string `string2` The second string ### Return Values Returns `-1` if `string1` is less than `string2`; `1` if `string1` is greater than `string2`, and `0` if they are equal. ### Changelog | Version | Description | | --- | --- | | 8.2.0 | This function now returns `-1` or `1`, where it previously returned a negative or positive number. | ### Examples **Example #1 **strcasecmp()** example** ``` <?php $var1 = "Hello"; $var2 = "hello"; if (strcasecmp($var1, $var2) == 0) {     echo '$var1 is equal to $var2 in a case-insensitive string comparison'; } ?> ``` ### See Also * [strcmp()](function.strcmp) - Binary safe string comparison * [preg\_match()](function.preg-match) - Perform a regular expression match * [substr\_compare()](function.substr-compare) - Binary safe comparison of two strings from an offset, up to length characters * [strncasecmp()](function.strncasecmp) - Binary safe case-insensitive string comparison of the first n characters * [stristr()](function.stristr) - Case-insensitive strstr * [substr()](function.substr) - Return part of a string php ReflectionFunctionAbstract::inNamespace ReflectionFunctionAbstract::inNamespace ======================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) ReflectionFunctionAbstract::inNamespace — Checks if function in namespace ### Description ``` public ReflectionFunctionAbstract::inNamespace(): bool ``` Checks whether a function is defined in a namespace. ### Parameters This function has no parameters. ### Return Values **`true`** if it's in a namespace, otherwise **`false`** ### See Also * [ReflectionFunctionAbstract::getNamespaceName()](reflectionfunctionabstract.getnamespacename) - Gets namespace name * [namespaces](https://www.php.net/manual/en/language.namespaces.php) php ArrayIterator::__construct ArrayIterator::\_\_construct ============================ (PHP 5, PHP 7, PHP 8) ArrayIterator::\_\_construct — Construct an ArrayIterator ### Description public **ArrayIterator::\_\_construct**(array|object `$array` = [], int `$flags` = 0) Constructs an [ArrayIterator](class.arrayiterator) object. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `array` The array or object to be iterated on. `flags` Flags to control the behaviour of the [ArrayIterator](class.arrayiterator) object. See [ArrayIterator::setFlags()](arrayiterator.setflags). ### See Also * [ArrayIterator::getArrayCopy()](arrayiterator.getarraycopy) - Get array copy php ReflectionFunction::__construct ReflectionFunction::\_\_construct ================================= (PHP 5, PHP 7, PHP 8) ReflectionFunction::\_\_construct — Constructs a ReflectionFunction object ### Description public **ReflectionFunction::\_\_construct**([Closure](class.closure)|string `$function`) Constructs a [ReflectionFunction](class.reflectionfunction) object. ### Parameters `function` The name of the function to reflect or a [closure](functions.anonymous). ### Errors/Exceptions A [ReflectionException](class.reflectionexception) if the `function` parameter does not contain a valid function. ### Examples **Example #1 **ReflectionFunction::\_\_construct()** example** ``` <?php /**  * A simple counter  *  * @return    int  */ function counter1() {     static $c = 0;     return ++$c; } /**  * Another simple counter  *  * @return    int  */ $counter2 = function() {     static $d = 0;     return ++$d; }; function dumpReflectionFunction($func) {     // Print out basic information     printf(         "\n\n===> The %s function '%s'\n".         "     declared in %s\n".         "     lines %d to %d\n",         $func->isInternal() ? 'internal' : 'user-defined',         $func->getName(),         $func->getFileName(),         $func->getStartLine(),         $func->getEndline()     );     // Print documentation comment     printf("---> Documentation:\n %s\n", var_export($func->getDocComment(), 1));     // Print static variables if existant     if ($statics = $func->getStaticVariables())     {         printf("---> Static variables: %s\n", var_export($statics, 1));     } } // Create an instance of the ReflectionFunction class dumpReflectionFunction(new ReflectionFunction('counter1')); dumpReflectionFunction(new ReflectionFunction($counter2)); ?> ``` The above example will output something similar to: ``` ===> The user-defined function 'counter1' declared in Z:\reflectcounter.php lines 7 to 11 ---> Documentation: '/** * A simple counter * * @return int */' ---> Static variables: array ( 'c' => 0, ) ===> The user-defined function '{closure}' declared in Z:\reflectcounter.php lines 18 to 23 ---> Documentation: '/** * Another simple counter * * @return int */' ---> Static variables: array ( 'd' => 0, ) ``` ### See Also * [ReflectionMethod::\_\_construct()](reflectionmethod.construct) - Constructs a ReflectionMethod * [Constructors](language.oop5.decon#language.oop5.decon.constructor) php Yaf_Request_Abstract::setModuleName Yaf\_Request\_Abstract::setModuleName ===================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::setModuleName — Set module name ### Description ``` public Yaf_Request_Abstract::setModuleName(string $module, bool $format_name = true): void ``` set module name to request, this is usually used by custom router to set route result module name. ### Parameters `module` string module name, it should be in camel style, like "Index" or "Foo\_Bar" `format_name` this is introduced in Yaf 3.2.0, by default Yaf will format the name into camel mode, if this is set to **`false`** , Yaf will set the original name to request. ### Return Values php odbc_field_len odbc\_field\_len ================ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_field\_len — Get the length (precision) of a field ### Description ``` odbc_field_len(resource $statement, int $field): int|false ``` Gets the length of the field referenced by number in the given result identifier. ### Parameters `statement` The result identifier. `field` The field number. Field numbering starts at 1. ### Return Values Returns the field length, or **`false`** on error. ### See Also * [odbc\_field\_scale()](function.odbc-field-scale) - Get the scale of a field to get the scale of a floating point number php ldap_get_entries ldap\_get\_entries ================== (PHP 4, PHP 5, PHP 7, PHP 8) ldap\_get\_entries — Get all result entries ### Description ``` ldap_get_entries(LDAP\Connection $ldap, LDAP\Result $result): array|false ``` Reads multiple entries from the given result, and then reading the attributes and multiple values. ### Parameters `ldap` An [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect). `result` An [LDAP\Result](class.ldap-result) instance, returned by [ldap\_list()](function.ldap-list) or [ldap\_search()](function.ldap-search). ### Return Values Returns a complete result information in a multi-dimensional array on success, or **`false`** on failure. The structure of the array is as follows. The attribute index is converted to lowercase. (Attributes are case-insensitive for directory servers, but not when used as array indices.) ``` return_value["count"] = number of entries in the result return_value[0] : refers to the details of first entry return_value[i]["dn"] = DN of the ith entry in the result return_value[i]["count"] = number of attributes in ith entry return_value[i][j] = NAME of the jth attribute in the ith entry in the result return_value[i]["attribute"]["count"] = number of values for attribute in ith entry return_value[i]["attribute"][j] = jth value of attribute in ith entry ``` ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.1.0 | The `result` parameter expects an [LDAP\Result](class.ldap-result) instance now; previously, a [resource](language.types.resource) was expected. | ### See Also * [ldap\_first\_entry()](function.ldap-first-entry) - Return first result id * [ldap\_next\_entry()](function.ldap-next-entry) - Get next result entry php Imagick::frameImage Imagick::frameImage =================== (PECL imagick 2, PECL imagick 3) Imagick::frameImage — Adds a simulated three-dimensional border ### Description ``` public Imagick::frameImage( mixed $matte_color, int $width, int $height, int $inner_bevel, int $outer_bevel ): bool ``` Adds a simulated three-dimensional border around the image. The width and height specify the border width of the vertical and horizontal sides of the frame. The inner and outer bevels indicate the width of the inner and outer shadows of the frame. ### Parameters `matte_color` ImagickPixel object or a string representing the matte color `width` The width of the border `height` The height of the border `inner_bevel` The inner bevel width `outer_bevel` The outer bevel width ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object. | ### Examples **Example #1 **Imagick::frameImage()**** ``` <?php function frameImage($imagePath, $color, $width, $height, $innerBevel, $outerBevel) {     $imagick = new \Imagick(realpath($imagePath));     $width = $width + $innerBevel + $outerBevel;     $height = $height + $innerBevel + $outerBevel;     $imagick->frameimage(         $color,         $width,         $height,         $innerBevel,         $outerBevel     );     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php imagecopyresampled imagecopyresampled ================== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) imagecopyresampled — Copy and resize part of an image with resampling ### Description ``` imagecopyresampled( GdImage $dst_image, GdImage $src_image, int $dst_x, int $dst_y, int $src_x, int $src_y, int $dst_width, int $dst_height, int $src_width, int $src_height ): bool ``` **imagecopyresampled()** copies a rectangular portion of one image to another image, smoothly interpolating pixel values so that, in particular, reducing the size of an image still retains a great deal of clarity. In other words, **imagecopyresampled()** will take a rectangular area from `src_image` of width `src_width` and height `src_height` at position (`src_x`,`src_y`) and place it in a rectangular area of `dst_image` of width `dst_width` and height `dst_height` at position (`dst_x`,`dst_y`). If the source and destination coordinates and width and heights differ, appropriate stretching or shrinking of the image fragment will be performed. The coordinates refer to the upper left corner. This function can be used to copy regions within the same image (if `dst_image` is the same as `src_image`) but if the regions overlap the results will be unpredictable. ### Parameters `dst_image` Destination image resource. `src_image` Source image resource. `dst_x` x-coordinate of destination point. `dst_y` y-coordinate of destination point. `src_x` x-coordinate of source point. `src_y` y-coordinate of source point. `dst_width` Destination width. `dst_height` Destination height. `src_width` Source width. `src_height` Source height. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `dst_image` and `src_image` expect [GdImage](class.gdimage) instances now; previously, resources were expected. | ### Examples **Example #1 Simple example** This example will resample an image to half its original size. ``` <?php // The file $filename = 'test.jpg'; $percent = 0.5; // Content type header('Content-Type: image/jpeg'); // Get new dimensions list($width, $height) = getimagesize($filename); $new_width = $width * $percent; $new_height = $height * $percent; // Resample $image_p = imagecreatetruecolor($new_width, $new_height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height); // Output imagejpeg($image_p, null, 100); ?> ``` The above example will output something similar to: **Example #2 Resampling an image proportionally** This example will display an image with the maximum width, or height, of 200 pixels. ``` <?php // The file $filename = 'test.jpg'; // Set a maximum height and width $width = 200; $height = 200; // Content type header('Content-Type: image/jpeg'); // Get new dimensions list($width_orig, $height_orig) = getimagesize($filename); $ratio_orig = $width_orig/$height_orig; if ($width/$height > $ratio_orig) {    $width = $height*$ratio_orig; } else {    $height = $width/$ratio_orig; } // Resample $image_p = imagecreatetruecolor($width, $height); $image = imagecreatefromjpeg($filename); imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width_orig, $height_orig); // Output imagejpeg($image_p, null, 100); ?> ``` The above example will output something similar to: ### Notes > > **Note**: > > > There is a problem due to palette image limitations (255+1 colors). Resampling or filtering an image commonly needs more colors than 255, a kind of approximation is used to calculate the new resampled pixel and its color. With a palette image we try to allocate a new color, if that failed, we choose the closest (in theory) computed color. This is not always the closest visual color. That may produce a weird result, like blank (or visually blank) images. To skip this problem, please use a truecolor image as a destination image, such as one created by [imagecreatetruecolor()](function.imagecreatetruecolor). > > ### See Also * [imagecopyresized()](function.imagecopyresized) - Copy and resize part of an image * [imagescale()](function.imagescale) - Scale an image using the given new width and height * [imagecrop()](function.imagecrop) - Crop an image to the given rectangle
programming_docs
php ReflectionEnum::__construct ReflectionEnum::\_\_construct ============================= (PHP 8 >= 8.1.0) ReflectionEnum::\_\_construct — Instantiates a [ReflectionEnum](class.reflectionenum) object ### Description public **ReflectionEnum::\_\_construct**(object|string `$objectOrClass`) ### Parameters `objectOrClass` An enum instance or a name. php SplObjectStorage::addAll SplObjectStorage::addAll ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplObjectStorage::addAll — Adds all objects from another storage ### Description ``` public SplObjectStorage::addAll(SplObjectStorage $storage): int ``` Adds all objects-data pairs from a different storage in the current storage. ### Parameters `storage` The storage you want to import. ### Return Values The number of objects in the storage. ### Examples **Example #1 **SplObjectStorage::addAll()** example** ``` <?php $o = new StdClass; $a = new SplObjectStorage(); $a[$o] = "hello"; $b = new SplObjectStorage(); $b->addAll($a); echo $b[$o]."\n"; ?> ``` The above example will output something similar to: ``` hello ``` ### See Also * [SplObjectStorage::removeAll()](splobjectstorage.removeall) - Removes objects contained in another storage from the current storage php The Parle\ParserException class The Parle\ParserException class =============================== Introduction ------------ (PECL parle >= 0.5.1) Class synopsis -------------- class **Parle\ParserException** extends [Exception](class.exception) implements [Throwable](class.throwable) { /\* Inherited properties \*/ protected string [$message](class.exception#exception.props.message) = ""; private string [$string](class.exception#exception.props.string) = ""; protected int [$code](class.exception#exception.props.code); protected string [$file](class.exception#exception.props.file) = ""; protected int [$line](class.exception#exception.props.line); private array [$trace](class.exception#exception.props.trace) = []; private ?[Throwable](class.throwable) [$previous](class.exception#exception.props.previous) = null; /\* Methods \*/ /\* Inherited methods \*/ ``` final public Exception::getMessage(): string ``` ``` final public Exception::getPrevious(): ?Throwable ``` ``` final public Exception::getCode(): int ``` ``` final public Exception::getFile(): string ``` ``` final public Exception::getLine(): int ``` ``` final public Exception::getTrace(): array ``` ``` final public Exception::getTraceAsString(): string ``` ``` public Exception::__toString(): string ``` ``` private Exception::__clone(): void ``` } php chmod chmod ===== (PHP 4, PHP 5, PHP 7, PHP 8) chmod — Changes file mode ### Description ``` chmod(string $filename, int $permissions): bool ``` Attempts to change the mode of the specified file to that given in `permissions`. ### Parameters `filename` Path to the file. `permissions` Note that `permissions` is not automatically assumed to be an octal value, so to ensure the expected operation, you need to prefix `permissions` with a zero (0). Strings such as "g+w" will not work properly. ``` <?php chmod("/somedir/somefile", 755);   // decimal; probably incorrect chmod("/somedir/somefile", "u+rwx,go+rx"); // string; incorrect chmod("/somedir/somefile", 0755);  // octal; correct value of mode ?> ``` The `permissions` parameter consists of three octal number components specifying access restrictions for the owner, the user group in which the owner is in, and to everybody else in this order. One component can be computed by adding up the needed permissions for that target user base. Number 1 means that you grant execute rights, number 2 means that you make the file writeable, number 4 means that you make the file readable. Add up these numbers to specify needed rights. You can also read more about modes on Unix systems with '**man 1 chmod**' and '**man 2 chmod**'. ``` <?php // Read and write for owner, nothing for everybody else chmod("/somedir/somefile", 0600); // Read and write for owner, read for everybody else chmod("/somedir/somefile", 0644); // Everything for owner, read and execute for others chmod("/somedir/somefile", 0755); // Everything for owner, read and execute for owner's group chmod("/somedir/somefile", 0750); ?> ``` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Notes > > **Note**: > > > The current user is the user under which PHP runs. It is probably not the same user you use for normal shell or FTP access. The mode can be changed only by user who owns the file on most systems. > > > **Note**: This function will not work on [remote files](https://www.php.net/manual/en/features.remote-files.php) as the file to be examined must be accessible via the server's filesystem. > > ### See Also * [chown()](function.chown) - Changes file owner * [chgrp()](function.chgrp) - Changes file group * [fileperms()](function.fileperms) - Gets file permissions * [stat()](function.stat) - Gives information about a file php mime_content_type mime\_content\_type =================== (PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8) mime\_content\_type — Detect MIME Content-type for a file ### Description ``` mime_content_type(resource|string $filename): string|false ``` Returns the MIME content type for a file as determined by using information from the magic.mime file. ### Parameters `filename` Path to the tested file. ### Return Values Returns the content type in MIME format, like `text/plain` or `application/octet-stream`, or **`false`** on failure. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 **mime\_content\_type()** Example** ``` <?php echo mime_content_type('php.gif') . "\n"; echo mime_content_type('test.php'); ?> ``` The above example will output: ``` image/gif text/plain ``` ### See Also * [finfo\_file()](finfo.file) - Alias of finfo\_file() * [finfo\_buffer()](finfo.buffer) - Alias of finfo\_buffer() php GearmanClient::ping GearmanClient::ping =================== (No version information available, might only be in Git) GearmanClient::ping — Send data to all job servers to see if they echo it back ### Description ``` public GearmanClient::ping(string $workload): bool ``` Sends some arbitrary data to all job servers to see if they echo it back. The data sent is not used or processed in any other way. Primarily used for testing and debugging. ### Parameters `workload` Some arbitrary serialized data to be echo back ### Return Values Returns **`true`** on success or **`false`** on failure. php mysqli_stmt::$num_rows mysqli\_stmt::$num\_rows ======================== mysqli\_stmt::num\_rows ======================= mysqli\_stmt\_num\_rows ======================= (PHP 5, PHP 7, PHP 8) mysqli\_stmt::$num\_rows -- mysqli\_stmt::num\_rows -- mysqli\_stmt\_num\_rows — Returns the number of rows fetched from the server ### Description Object-oriented style int|string [$mysqli\_stmt->num\_rows](mysqli-stmt.num-rows); ``` public mysqli_stmt::num_rows(): int|string ``` Procedural style ``` mysqli_stmt_num_rows(mysqli_stmt $statement): int|string ``` Returns the number of rows buffered in the statement. This function will only work after [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) is called to buffer the entire result set in the statement handle. This function returns `0` unless all rows have been fetched from the server. ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). ### Return Values An int representing the number of buffered rows. Returns `0` in unbuffered mode unless all rows have been fetched from the server. > > **Note**: > > > If the number of rows is greater than **`PHP_INT_MAX`**, the number will be returned as a string. > > > ### Examples **Example #1 Object-oriented style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; $stmt = $mysqli->prepare($query); $stmt->execute(); /* store the result in an internal buffer */ $stmt->store_result(); printf("Number of rows: %d.\n", $stmt->num_rows); ``` **Example #2 Procedural style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $query = "SELECT Name, CountryCode FROM City ORDER BY Name LIMIT 20"; $stmt = mysqli_prepare($link, $query); mysqli_stmt_execute($stmt); /* store the result in an internal buffer */ mysqli_stmt_store_result($stmt); printf("Number of rows: %d.\n", mysqli_stmt_num_rows($stmt)); ``` The above examples will output: ``` Number of rows: 20. ``` ### See Also * [mysqli\_stmt\_store\_result()](mysqli-stmt.store-result) - Stores a result set in an internal buffer * [mysqli\_stmt\_affected\_rows()](mysqli-stmt.affected-rows) - Returns the total number of rows changed, deleted, inserted, or matched by the last statement executed * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution php Gmagick::setimagecompose Gmagick::setimagecompose ======================== (PECL gmagick >= Unknown) Gmagick::setimagecompose — Sets the image composite operator ### Description ``` public Gmagick::setimagecompose(int $composite): Gmagick ``` Sets the image composite operator. ### Parameters `composite` The image composite operator. ### Return Values The Gmagick object on success ### Errors/Exceptions Throws an **GmagickException** on error. php ReflectionClass::newInstanceArgs ReflectionClass::newInstanceArgs ================================ (PHP 5 >= 5.1.3, PHP 7, PHP 8) ReflectionClass::newInstanceArgs — Creates a new class instance from given arguments ### Description ``` public ReflectionClass::newInstanceArgs(array $args = []): ?object ``` Creates a new instance of the class, the given arguments are passed to the class constructor. ### Parameters `args` The parameters to be passed to the class constructor as an array. ### Return Values Returns a new instance of the class, or **`null`** on failure. ### Errors/Exceptions A [ReflectionException](class.reflectionexception) if the class constructor is not public. A [ReflectionException](class.reflectionexception) if the class does not have a constructor and the `args` parameter contains one or more parameters. ### Examples **Example #1 Basic usage of **ReflectionClass::newInstanceArgs()**** ``` <?php $class = new ReflectionClass('ReflectionFunction'); $instance = $class->newInstanceArgs(array('substr')); var_dump($instance); ?> ``` The above example will output: ``` object(ReflectionFunction)#2 (1) { ["name"]=> string(6) "substr" } ``` ### See Also * [ReflectionClass::newInstance()](reflectionclass.newinstance) - Creates a new class instance from given arguments * [ReflectionClass::newInstanceWithoutConstructor()](reflectionclass.newinstancewithoutconstructor) - Creates a new class instance without invoking the constructor php ReflectionClass::hasMethod ReflectionClass::hasMethod ========================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) ReflectionClass::hasMethod — Checks if method is defined ### Description ``` public ReflectionClass::hasMethod(string $name): bool ``` Checks whether a specific method is defined in a class. ### Parameters `name` Name of the method being checked for. ### Return Values **`true`** if it has the method, otherwise **`false`** ### Examples **Example #1 **ReflectionClass::hasMethod()** example** ``` <?php Class C {     public function publicFoo() {         return true;     }     protected function protectedFoo() {         return true;     }     private function privateFoo() {         return true;     }     static function staticFoo() {         return true;     } } $rc = new ReflectionClass("C"); var_dump($rc->hasMethod('publicFoo')); var_dump($rc->hasMethod('protectedFoo')); var_dump($rc->hasMethod('privateFoo')); var_dump($rc->hasMethod('staticFoo')); // C should not have method bar var_dump($rc->hasMethod('bar')); // Method names are case insensitive var_dump($rc->hasMethod('PUBLICfOO')); ?> ``` The above example will output: ``` bool(true) bool(true) bool(true) bool(true) bool(false) bool(true) ``` ### See Also * [ReflectionClass::hasConstant()](reflectionclass.hasconstant) - Checks if constant is defined * [ReflectionClass::hasProperty()](reflectionclass.hasproperty) - Checks if property is defined php gc_collect_cycles gc\_collect\_cycles =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) gc\_collect\_cycles — Forces collection of any existing garbage cycles ### Description ``` gc_collect_cycles(): int ``` Forces collection of any existing garbage cycles. ### Parameters This function has no parameters. ### Return Values Returns number of collected cycles. ### See Also * [Garbage Collection](https://www.php.net/manual/en/features.gc.php) php SolrQuery::getTerms SolrQuery::getTerms =================== (PECL solr >= 0.9.2) SolrQuery::getTerms — Returns whether or not the TermsComponent is enabled ### Description ``` public SolrQuery::getTerms(): bool ``` Returns whether or not the TermsComponent is enabled ### Parameters This function has no parameters. ### Return Values Returns a boolean on success and **`null`** if not set. php Componere\Definition::register Componere\Definition::register ============================== (Componere 2 >= 2.1.0) Componere\Definition::register — Registration ### Description ``` public Componere\Definition::register(): void ``` Shall register the current Definition ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if Definition was registered php IntlChar::isprint IntlChar::isprint ================= (PHP 7, PHP 8) IntlChar::isprint — Check if code point is a printable character ### Description ``` public static IntlChar::isprint(int|string $codepoint): ?bool ``` Determines whether the specified code point is a printable character. **`true`** for general categories other than "C" (controls). ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is a printable character, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isprint("A")); var_dump(IntlChar::isprint(" ")); var_dump(IntlChar::isprint("\n")); var_dump(IntlChar::isprint("\u{200e}")); ?> ``` The above example will output: ``` bool(true) bool(true) bool(false) bool(false) ``` ### See Also * [IntlChar::iscntrl()](intlchar.iscntrl) - Check if code point is a control character * **`IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`** php eio_event_loop eio\_event\_loop ================ (PECL eio >= 0.0.1dev) eio\_event\_loop — Polls libeio until all requests proceeded ### Description ``` eio_event_loop(): bool ``` **eio\_event\_loop()** polls libeio until all requests proceeded. ### Parameters This function has no parameters. ### Return Values **eio\_event\_loop()** returns **`true`** on success, or **`false`** on failure. ### Examples **Example #1 **eio\_event\_loop()** example** ``` <?php $temp_filename = "eio-temp-file.tmp"; touch($temp_filename); /* Is called when eio_chmod() finished */ function my_chmod_callback($data, $result) {     global $temp_filename;     if ($result == 0 && !is_readable($temp_filename) && is_writable($temp_filename)) {         echo "eio_chmod_ok";     }     @unlink($temp_filename); } eio_chmod($temp_filename, 0200, EIO_PRI_DEFAULT, "my_chmod_callback"); eio_event_loop(); ?> ``` The above example will output something similar to: ``` eio_chmod_ok ``` ### See Also * [eio\_poll()](function.eio-poll) - Can be to be called whenever there are pending requests that need finishing php ArrayIterator::valid ArrayIterator::valid ==================== (PHP 5, PHP 7, PHP 8) ArrayIterator::valid — Check whether array contains more entries ### Description ``` public ArrayIterator::valid(): bool ``` Checks if the array contains any more entries. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the iterator is valid, otherwise **`false`** ### Examples **Example #1 **ArrayIterator::valid()** example** ``` <?php $array = array('1' => 'one'); $arrayobject = new ArrayObject($array); $iterator = $arrayobject->getIterator(); var_dump($iterator->valid()); //bool(true) $iterator->next(); // advance to the next item //bool(false) because there is only one array element var_dump($iterator->valid()); ?> ``` php SVMModel::__construct SVMModel::\_\_construct ======================= (PECL svm >= 0.1.0) SVMModel::\_\_construct — Construct a new SVMModel ### Description public **SVMModel::\_\_construct**(string `$filename` = ?) Build a new SVMModel. Models will usually be created from the SVM::train function, but then saved models may be restored directly. ### Parameters `filename` The filename for the saved model file this model should load. ### Errors/Exceptions Throws a **SVMException** on error ### See Also * [SVMModel::load()](svmmodel.load) - Load a saved SVM Model php grapheme_stripos grapheme\_stripos ================= (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) grapheme\_stripos — Find position (in grapheme units) of first occurrence of a case-insensitive string ### Description Procedural style ``` grapheme_stripos(string $haystack, string $needle, int $offset = 0): int|false ``` Find position (in grapheme units) of first occurrence of a case-insensitive string ### Parameters `haystack` The string to look in. Must be valid UTF-8. `needle` The string to look for. Must be valid UTF-8. `offset` The optional `offset` parameter allows you to specify where in `haystack` to start searching as an offset in grapheme units (not bytes or characters). If the offset is negative, it is treated relative to the end of the string. The position returned is still relative to the beginning of `haystack` regardless of the value of `offset`. ### Return Values Returns the position as an integer. If `needle` is not found, **grapheme\_stripos()** will return **`false`**. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | Support for negative `offset`s has been added. | ### Examples **Example #1 **grapheme\_stripos()** example** ``` <?php $char_a_ring_nfd = "a\xCC\x8A";  // 'LATIN SMALL LETTER A WITH RING ABOVE' (U+00E5) normalization form "D" $char_o_diaeresis_nfd = "o\xCC\x88"; // 'LATIN SMALL LETTER O WITH DIAERESIS' (U+00F6) normalization form "D" $char_O_diaeresis_nfd = "O\xCC\x88"; // 'LATIN CAPITAL LETTER O WITH DIAERESIS' (U+00D6) normalization form "D" print grapheme_stripos( $char_a_ring_nfd . $char_a_ring_nfd . $char_o_diaeresis_nfd, $char_O_diaeresis_nfd); ?> ``` The above example will output: ``` 2 ``` ### See Also * [grapheme\_stristr()](function.grapheme-stristr) - Returns part of haystack string from the first occurrence of case-insensitive needle to the end of haystack * [grapheme\_strpos()](function.grapheme-strpos) - Find position (in grapheme units) of first occurrence of a string * [grapheme\_strripos()](function.grapheme-strripos) - Find position (in grapheme units) of last occurrence of a case-insensitive string * [grapheme\_strrpos()](function.grapheme-strrpos) - Find position (in grapheme units) of last occurrence of a string * [grapheme\_strstr()](function.grapheme-strstr) - Returns part of haystack string from the first occurrence of needle to the end of haystack * [» Unicode Text Segmentation: Grapheme Cluster Boundaries](http://unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries)
programming_docs
php ImagickPixel::setColor ImagickPixel::setColor ====================== (PECL imagick 2, PECL imagick 3) ImagickPixel::setColor — Sets the color ### Description ``` public ImagickPixel::setColor(string $color): bool ``` **Warning**This function is currently not documented; only its argument list is available. Sets the color described by the ImagickPixel object, with a string (e.g. "blue", "#0000ff", "rgb(0,0,255)", "cmyk(100,100,100,10)", etc.). ### Parameters `color` The color definition to use in order to initialise the ImagickPixel object. ### Return Values Returns **`true`** if the specified color was set, **`false`** otherwise. ### Examples **Example #1 **ImagickPixel::setColor()**** ``` <?php function setColor() {     $draw = new \ImagickDraw();     $strokeColor = new \ImagickPixel('green');     $fillColor = new \ImagickPixel();     $fillColor->setColor('rgba(100%, 75%, 0%, 1.0)');     $draw->setstrokewidth(3.0);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->rectangle(200, 200, 300, 300);     $image = new \Imagick();     $image->newImage(500, 500, "SteelBlue2");     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php UConverter::setSubstChars UConverter::setSubstChars ========================= (PHP 5 >= 5.5.0, PHP 7, PHP 8, PECL >= 3.0.0a1) UConverter::setSubstChars — Set the substitution chars ### Description ``` public UConverter::setSubstChars(string $chars): bool ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `chars` ### Return Values php passthru passthru ======== (PHP 4, PHP 5, PHP 7, PHP 8) passthru — Execute an external program and display raw output ### Description ``` passthru(string $command, int &$result_code = null): ?false ``` The **passthru()** function is similar to the [exec()](function.exec) function in that it executes a `command`. This function should be used in place of [exec()](function.exec) or [system()](function.system) when the output from the Unix command is binary data which needs to be passed directly back to the browser. A common use for this is to execute something like the pbmplus utilities that can output an image stream directly. By setting the Content-type to `image/gif` and then calling a pbmplus program to output a gif, you can create PHP scripts that output images directly. ### Parameters `command` The command that will be executed. `result_code` If the `result_code` argument is present, the return status of the Unix command will be placed here. ### Return Values Returns **`null`** on success or **`false`** on failure. ### Errors/Exceptions Will emit an **`E_WARNING`** if **passthru()** is unable to execute the `command`. Throws a [ValueError](class.valueerror) if `command` is empty or contains null bytes. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | If `command` is empty or contains null bytes, **passthru()** now throws a [ValueError](class.valueerror). Previously it emitted an **`E_WARNING`** and returned **`false`**. | ### Notes **Warning**When allowing user-supplied data to be passed to this function, use [escapeshellarg()](function.escapeshellarg) or [escapeshellcmd()](function.escapeshellcmd) to ensure that users cannot trick the system into executing arbitrary commands. > > **Note**: > > > If a program is started with this function, in order for it to continue running in the background, the output of the program must be redirected to a file or another output stream. Failing to do so will cause PHP to hang until the execution of the program ends. > > > ### See Also * [exec()](function.exec) - Execute an external program * [system()](function.system) - Execute an external program and display the output * [popen()](function.popen) - Opens process file pointer * [escapeshellcmd()](function.escapeshellcmd) - Escape shell metacharacters * [backtick operator](language.operators.execution) php ldap_modify_batch ldap\_modify\_batch =================== (PHP 5.4 >= 5.4.26, PHP 5.5 >= 5.5.10, PHP 5.6 >= 5.6.0, PHP 7, PHP 8) ldap\_modify\_batch — Batch and execute modifications on an LDAP entry ### Description ``` ldap_modify_batch( LDAP\Connection $ldap, string $dn, array $modifications_info, ?array $controls = null ): bool ``` Modifies an existing entry in the LDAP directory. Allows detailed specification of the modifications to perform. ### Parameters `ldap` An LDAP resource, returned by [ldap\_connect()](function.ldap-connect). `dn` The distinguished name of an LDAP entity. `modifications_info` An array that specifies the modifications to make. Each entry in this array is an associative array with two or three keys: `attrib` maps to the name of the attribute to modify, `modtype` maps to the type of modification to perform, and (depending on the type of modification) `values` maps to an array of attribute values relevant to the modification. Possible values for `modtype` include: **`LDAP_MODIFY_BATCH_ADD`** Each value specified through `values` is added (as an additional value) to the attribute named by `attrib`. **`LDAP_MODIFY_BATCH_REMOVE`** Each value specified through `values` is removed from the attribute named by `attrib`. Any value of the attribute not contained in the `values` array will remain untouched. **`LDAP_MODIFY_BATCH_REMOVE_ALL`** All values are removed from the attribute named by `attrib`. A `values` entry must not be provided. **`LDAP_MODIFY_BATCH_REPLACE`** All current values of the attribute named by `attrib` are replaced with the values specified through `values`. Note that any value for `attrib` must be a string, any value for `values` must be an array of strings, and any value for `modtype` must be one of the LDAP\_MODIFY\_BATCH\_\* constants listed above. `controls` Array of [LDAP Controls](https://www.php.net/manual/en/ldap.controls.php) to send with the request. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | | 8.0.0 | `controls` is nullable now; previously, it defaulted to `[]`. | | 7.3.0 | Support for `controls` added | ### Examples **Example #1 Add a telephone number to a contact** ``` <?php $dn = "cn=John Smith,ou=Wizards,dc=example,dc=com"; $modifs = [     [         "attrib"  => "telephoneNumber",         "modtype" => LDAP_MODIFY_BATCH_ADD,         "values"  => ["+1 555 555 1717"],     ], ]; ldap_modify_batch($connection, $dn, $modifs); ?> ``` **Example #2 Rename a user** ``` <?php $dn = "cn=John Smith,ou=Wizards,dc=example,dc=com"; $modifs = [     [         "attrib"  => "sn",         "modtype" => LDAP_MODIFY_BATCH_REPLACE,         "values"  => ["Smith-Jones"],     ],     [         "attrib"  => "givenName",         "modtype" => LDAP_MODIFY_BATCH_REPLACE,         "values"  => ["Jack"],     ], ]; ldap_modify_batch($connection, $dn, $modifs); ldap_rename($connection, $dn, "cn=Jack Smith-Jones", NULL, TRUE); ?> ``` **Example #3 Add two e-mail addresses to a user** ``` <?php $dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com"; $modifs = [     [         "attrib"  => "mail",         "modtype" => LDAP_MODIFY_BATCH_ADD,         "values"  => [             "[email protected]",             "[email protected]",         ],     ], ]; ldap_modify_batch($connection, $dn, $modifs); ?> ``` **Example #4 Change a user's password** ``` <?php $dn = "cn=Jack Smith-Jones,ou=Wizards,dc=example,dc=com"; $modifs = [     [         "attrib"  => "userPassword",         "modtype" => LDAP_MODIFY_BATCH_REMOVE,         "values"  => ["Tr0ub4dor&3"],     ],     [         "attrib"  => "userPassword",         "modtype" => LDAP_MODIFY_BATCH_ADD,         "values"  => ["correct horse battery staple"],     ], ]; ldap_modify_batch($connection, $dn, $modifs); ?> ``` **Example #5 Change a user's password (Active Directory)** ``` <?php function adifyPw($pw) {     return iconv("UTF-8", "UTF-16LE", '"' . $pw . '"'); } $dn = "cn=Jack Smith-Jones,ou=Wizards,dc=ad,dc=example,dc=com"; $modifs = [     [         "attrib"  => "unicodePwd",         "modtype" => LDAP_MODIFY_BATCH_REMOVE,         "values"  => [adifyPw("Tr0ub4dor&3")],     ],     [         "attrib"  => "unicodePwd",         "modtype" => LDAP_MODIFY_BATCH_ADD,         "values"  => [adifyPw("correct horse battery staple")],     ], ]; ldap_modify_batch($connection, $dn, $modifs); ``` php SplHeap::count SplHeap::count ============== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplHeap::count — Counts the number of elements in the heap ### Description ``` public SplHeap::count(): int ``` ### Parameters This function has no parameters. ### Return Values Returns the number of elements in the heap. php EvCheck::createStopped EvCheck::createStopped ====================== (PECL ev >= 0.2.0) EvCheck::createStopped — Create instance of a stopped EvCheck watcher ### Description ``` final public static EvCheck::createStopped( string $callback , string $data = ?, string $priority = ?): object ``` Create instance of a stopped EvCheck watcher ### Parameters `callback` See [Watcher callbacks](https://www.php.net/manual/en/ev.watcher-callbacks.php) . `data` Custom data associated with the watcher. `priority` [Watcher priority](class.ev#ev.constants.watcher-pri) ### Return Values Returns EvCheck object on success. ### See Also * [EvPrepare](class.evprepare) php DirectoryIterator::key DirectoryIterator::key ====================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::key — Return the key for the current DirectoryIterator item ### Description ``` public DirectoryIterator::key(): mixed ``` Get the key for the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values The key for the current [DirectoryIterator](class.directoryiterator) item as an int. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | When the iterator is uninitialized, an [Error](class.error) is thrown now. Previously, the method returned **`false`**. | ### Examples **Example #1 A **DirectoryIterator::key()** example** ``` <?php $dir = new DirectoryIterator(dirname(__FILE__)); foreach ($dir as $fileinfo) {     if (!$fileinfo->isDot()) {         echo $fileinfo->key() . " => " . $fileinfo->getFilename() . "\n";     } } ?> ``` The above example will output something similar to: ``` 0 => apple.jpg 1 => banana.jpg 2 => index.php 3 => pear.jpg ``` ### See Also * [DirectoryIterator::current()](directoryiterator.current) - Return the current DirectoryIterator item * [DirectoryIterator::next()](directoryiterator.next) - Move forward to next DirectoryIterator item * [DirectoryIterator::rewind()](directoryiterator.rewind) - Rewind the DirectoryIterator back to the start * [DirectoryIterator::valid()](directoryiterator.valid) - Check whether current DirectoryIterator position is a valid file * [Iterator::key()](iterator.key) - Return the key of the current element php EventHttpRequest::closeConnection EventHttpRequest::closeConnection ================================= (PECL event >= 1.8.0) EventHttpRequest::closeConnection — Closes associated HTTP connection ### Description ``` public EventHttpRequest::closeConnection(): void ``` Closes HTTP connection associated with the request. ### Parameters This function has no parameters. ### Return Values No value is returned. php pcntl_signal pcntl\_signal ============= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_signal — Installs a signal handler ### Description ``` pcntl_signal(int $signal, callable|int $handler, bool $restart_syscalls = true): bool ``` The **pcntl\_signal()** function installs a new signal handler or replaces the current signal handler for the signal indicated by `signal`. ### Parameters `signal` The signal number. `handler` The signal handler. This may be either a [callable](language.types.callable), which will be invoked to handle the signal, or either of the two global constants **`SIG_IGN`** or **`SIG_DFL`**, which will ignore the signal or restore the default signal handler respectively. If a [callable](language.types.callable) is given, it must implement the following signature: ``` handler(int $signo, mixed $siginfo): void ``` `signal` The signal being handled. `siginfo` If operating systems supports siginfo\_t structures, this will be an array of signal information dependent on the signal. > > **Note**: > > > Note that when you set a handler to an object method, that object's reference count is increased which makes it persist until you either change the handler to something else, or your script ends. > > `restart_syscalls` Specifies whether system call restarting should be used when this signal arrives. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 7.1.0 | As of PHP 7.1.0 the handler callback is given a second argument containing the siginfo of the specific signal. This data is only supplied if the operating system has the siginfo\_t structure. If the OS does not implement siginfo\_t NULL is supplied. | ### Examples **Example #1 **pcntl\_signal()** example** ``` <?php // tick use required declare(ticks = 1); // signal handler function function sig_handler($signo) {      switch ($signo) {          case SIGTERM:              // handle shutdown tasks              exit;              break;          case SIGHUP:              // handle restart tasks              break;          case SIGUSR1:              echo "Caught SIGUSR1...\n";              break;          default:              // handle all other signals      } } echo "Installing signal handler...\n"; // setup signal handlers pcntl_signal(SIGTERM, "sig_handler"); pcntl_signal(SIGHUP,  "sig_handler"); pcntl_signal(SIGUSR1, "sig_handler"); // or use an object // pcntl_signal(SIGUSR1, array($obj, "do_something")); echo"Generating signal SIGUSR1 to self...\n"; // send SIGUSR1 to current process id // posix_* functions require the posix extension posix_kill(posix_getpid(), SIGUSR1); echo "Done\n"; ?> ``` ### Notes **pcntl\_signal()** doesn't stack the signal handlers, but replaces them. ### See Also * [pcntl\_fork()](function.pcntl-fork) - Forks the currently running process * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child php Stomp::abort Stomp::abort ============ stomp\_abort ============ (PECL stomp >= 0.1.0) Stomp::abort -- stomp\_abort — Rolls back a transaction in progress ### Description Object-oriented style (method): ``` public Stomp::abort(string $transaction_id, array $headers = ?): bool ``` Procedural style: ``` stomp_abort(resource $link, string $transaction_id, array $headers = ?): bool ``` Rolls back a transaction in progress. ### Parameters `link` Procedural style only: The stomp link identifier returned by [stomp\_connect()](stomp.construct). `transaction_id` The transaction to abort. `headers` Associative array containing the additional headers (example: receipt). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Object-oriented style** ``` <?php /* connection */ try {     $stomp = new Stomp('tcp://localhost:61613'); } catch(StompException $e) {     die('Connection failed: ' . $e->getMessage()); } /* begin a transaction */ $stomp->begin('t1'); /* send a message to the queue */ $stomp->send('/queue/foo', 'bar', array('transaction' => 't1')); /* rollback */ $stomp->abort('t1'); /* close connection */ unset($stomp); ?> ``` **Example #2 Procedural style** ``` <?php /* connection */ $link = stomp_connect('tcp://localhost:61613'); /* check connection */ if (!$link) {     die('Connection failed: ' . stomp_connect_error()); } /* begin a transaction */ stomp_begin($link, 't1'); /* send a message to the queue 'foo' */ stomp_send($link, '/queue/foo', 'bar', array('transaction' => 't1')); /* rollback */ stomp_abort($link, 't1'); /* close connection */ stomp_close($link); ?> ``` ### Notes **Tip**Stomp is inherently asynchronous. Synchronous communication can be implemented adding a receipt header. This will cause methods to not return anything until the server has acknowledged receipt of the message or until read timeout was reached. php DateTime::__construct DateTime::\_\_construct ======================= (PHP 5 >= 5.2.0, PHP 7, PHP 8) DateTime::\_\_construct — Returns new DateTime object ### Description public **DateTime::\_\_construct**(string `$datetime` = "now", ?[DateTimeZone](class.datetimezone) `$timezone` = **`null`**) Like [DateTimeImmutable::\_\_construct()](datetimeimmutable.construct) but works with [DateTime](class.datetime). Consider using the [DateTimeImmutable](class.datetimeimmutable) and features instead. Returns a new DateTime object. ### Parameters `datetime` A date/time string. Valid formats are explained in [Date and Time Formats](https://www.php.net/manual/en/datetime.formats.php). Enter `"now"` here to obtain the current time when using the `$timezone` parameter. `timezone` A [DateTimeZone](class.datetimezone) object representing the timezone of `$datetime`. If `$timezone` is omitted or **`null`**, the current timezone will be used. > > **Note**: > > > The `$timezone` parameter and the current timezone are ignored when the `$datetime` parameter either is a UNIX timestamp (e.g. `@946684800`) or specifies a timezone (e.g. `2010-01-28T15:00:00+02:00`). > > ### Return Values Returns a new DateTime instance. Procedural style returns **`false`** on failure. ### See Also * [DateTimeImmutable::\_\_construct()](datetimeimmutable.construct) - Returns new DateTimeImmutable object php php_strip_whitespace php\_strip\_whitespace ====================== (PHP 5, PHP 7, PHP 8) php\_strip\_whitespace — Return source with stripped comments and whitespace ### Description ``` php_strip_whitespace(string $filename): string ``` Returns the PHP source code in `filename` with PHP comments and whitespace removed. This may be useful for determining the amount of actual code in your scripts compared with the amount of comments. This is similar to using **php -w** from the [commandline](https://www.php.net/manual/en/features.commandline.php). ### Parameters `filename` Path to the PHP file. ### Return Values The stripped source code will be returned on success, or an empty string on failure. > > **Note**: > > > This function respects the value of the [short\_open\_tag](https://www.php.net/manual/en/ini.core.php#ini.short-open-tag) ini directive. > > ### Examples **Example #1 **php\_strip\_whitespace()** example** ``` <?php // PHP comment here /*  * Another PHP comment  */ echo        php_strip_whitespace(__FILE__); // Newlines are considered whitespace, and are removed too: do_nothing(); ?> ``` The above example will output: ``` <?php echo php_strip_whitespace(__FILE__); do_nothing(); ?> ``` Notice the PHP comments are gone, as are the whitespace and newline after the first echo statement.
programming_docs
php pcntl_sigwaitinfo pcntl\_sigwaitinfo ================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) pcntl\_sigwaitinfo — Waits for signals ### Description ``` pcntl_sigwaitinfo(array $signals, array &$info = []): int|false ``` The **pcntl\_sigwaitinfo()** function suspends execution of the calling script until one of the signals given in `signals` are delivered. If one of the signal is already pending (e.g. blocked by [pcntl\_sigprocmask()](function.pcntl-sigprocmask)), **pcntl\_sigwaitinfo()** will return immediately. ### Parameters `signals` Array of signals to wait for. `info` The `info` parameter is set to an array containing information about the signal. The following elements are set for all signals: * signo: Signal number * errno: An error number * code: Signal code The following elements may be set for the **`SIGCHLD`** signal: * status: Exit value or signal * utime: User time consumed * stime: System time consumed * pid: Sending process ID * uid: Real user ID of sending process The following elements may be set for the **`SIGILL`**, **`SIGFPE`**, **`SIGSEGV`** and **`SIGBUS`** signals: * addr: Memory location which caused fault The following element may be set for the **`SIGPOLL`** signal: * band: Band event * fd: File descriptor number ### Return Values Returns a signal number on success, or **`false`** on failure. ### Examples **Example #1 **pcntl\_sigwaitinfo()** example** ``` <?php echo "Blocking SIGHUP signal\n"; pcntl_sigprocmask(SIG_BLOCK, array(SIGHUP)); echo "Sending SIGHUP to self\n"; posix_kill(posix_getpid(), SIGHUP); echo "Waiting for signals\n"; $info = array(); pcntl_sigwaitinfo(array(SIGHUP), $info); ?> ``` ### See Also * [pcntl\_sigprocmask()](function.pcntl-sigprocmask) - Sets and retrieves blocked signals * [pcntl\_sigtimedwait()](function.pcntl-sigtimedwait) - Waits for signals, with a timeout php radius_get_tagged_attr_tag radius\_get\_tagged\_attr\_tag ============================== (PECL radius >= 1.3.0) radius\_get\_tagged\_attr\_tag — Extracts the tag from a tagged attribute ### Description ``` radius_get_tagged_attr_tag(string $data): int|false ``` If a tagged attribute has been returned from [radius\_get\_attr()](function.radius-get-attr), [radius\_get\_tagged\_attr\_data()](function.radius-get-tagged-attr-data) will return the tag from the attribute. ### Parameters `data` The tagged attribute to be decoded. ### Return Values Returns the tag from the tagged attribute or **`false`** on failure. ### Examples **Example #1 **radius\_get\_tagged\_attr\_tag()** example** ``` <?php while ($resa = radius_get_attr($res)) {     if (!is_array($resa)) {         printf ("Error getting attribute: %s\n",  radius_strerror($res));         exit;     }     $attr = $resa['attr'];     $data = $resa['data'];     $tag = radius_get_tagged_attr_tag($data);     $value = radius_get_tagged_attr_data($data);     printf("Got tagged attribute with tag %d and value %s\n", $tag, $value); } ?> ``` ### See Also * [radius\_get\_attr()](function.radius-get-attr) - Extracts an attribute * [radius\_get\_tagged\_attr\_data()](function.radius-get-tagged-attr-data) - Extracts the data from a tagged attribute php GearmanTask::returnCode GearmanTask::returnCode ======================= (PECL gearman >= 0.5.0) GearmanTask::returnCode — Get the last return code ### Description ``` public GearmanTask::returnCode(): int ``` Returns the last Gearman return code for this task. ### Parameters This function has no parameters. ### Return Values A valid Gearman return code. ### See Also * [GearmanClient::returnCode()](gearmanclient.returncode) - Get the last Gearman return code php get_resource_type get\_resource\_type =================== (PHP 4 >= 4.0.2, PHP 5, PHP 7, PHP 8) get\_resource\_type — Returns the resource type ### Description ``` get_resource_type(resource $resource): string ``` This function gets the type of the given resource. ### Parameters `resource` The evaluated resource handle. ### Return Values If the given `resource` is a resource, this function will return a string representing its type. If the type is not identified by this function, the return value will be the string `Unknown`. This function will return **`null`** and generate an error if `resource` is not a resource. ### Examples **Example #1 **get\_resource\_type()** example** ``` <?php $fp = fopen("foo", "w"); echo get_resource_type($fp) . "\n"; // As of PHP 8.0.0, the following does not work anymore. The curl_init function returns a CurlHandle object now. $c = curl_init(); echo get_resource_type($c) . "\n"; ?> ``` Output of the above example in PHP 7: ``` stream curl ``` ### See Also * [get\_resource\_id()](function.get-resource-id) - Returns an integer identifier for the given resource php Yaf_Dispatcher::enableView Yaf\_Dispatcher::enableView =========================== (Yaf >=1.0.0) Yaf\_Dispatcher::enableView — Enable view rendering ### Description ``` public Yaf_Dispatcher::enableView(): Yaf_Dispatcher ``` ### Parameters This function has no parameters. ### Return Values php ssh2_exec ssh2\_exec ========== (PECL ssh2 >= 0.9.0) ssh2\_exec — Execute a command on a remote server ### Description ``` ssh2_exec( resource $session, string $command, string $pty = ?, array $env = ?, int $width = 80, int $height = 25, int $width_height_type = SSH2_TERM_UNIT_CHARS ): resource|false ``` Execute a command at the remote end and allocate a channel for it. ### Parameters `session` An SSH connection link identifier, obtained from a call to [ssh2\_connect()](function.ssh2-connect). `command` `pty` `env` `env` may be passed as an associative array of name/value pairs to set in the target environment. `width` Width of the virtual terminal. `height` Height of the virtual terminal. `width_height_type` `width_height_type` should be one of **`SSH2_TERM_UNIT_CHARS`** or **`SSH2_TERM_UNIT_PIXELS`**. ### Return Values Returns a stream on success or **`false`** on failure. ### Examples **Example #1 Executing a command** ``` <?php $connection = ssh2_connect('shell.example.com', 22); ssh2_auth_password($connection, 'username', 'password'); $stream = ssh2_exec($connection, '/usr/local/bin/php -i'); ?> ``` ### See Also * [ssh2\_connect()](function.ssh2-connect) - Connect to an SSH server * [ssh2\_shell()](function.ssh2-shell) - Request an interactive shell * [ssh2\_tunnel()](function.ssh2-tunnel) - Open a tunnel through a remote server php SolrUtils::queryPhrase SolrUtils::queryPhrase ====================== (PECL solr >= 0.9.2) SolrUtils::queryPhrase — Prepares a phrase from an unescaped lucene string ### Description ``` public static SolrUtils::queryPhrase(string $str): string ``` Prepares a phrase from an unescaped lucene string. ### Parameters `str` The lucene phrase. ### Return Values Returns the phrase contained in double quotes. php reset reset ===== (PHP 4, PHP 5, PHP 7, PHP 8) reset — Set the internal pointer of an array to its first element ### Description ``` reset(array|object &$array): mixed ``` **reset()** rewinds `array`'s internal pointer to the first element and returns the value of the first array element. ### Parameters `array` The input array. ### Return Values Returns the value of the first array element, or **`false`** if the array is empty. **Warning**This function may return Boolean **`false`**, but may also return a non-Boolean value which evaluates to **`false`**. Please read the section on [Booleans](language.types.boolean) for more information. Use [the === operator](language.operators.comparison) for testing the return value of this function. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Calling this function on objects is deprecated. Either use [get\_mangled\_object\_vars()](function.get-mangled-object-vars) on the object first, or use [ArrayIterator](class.arrayiterator). | ### Examples **Example #1 **reset()** example** ``` <?php $array = array('step one', 'step two', 'step three', 'step four'); // by default, the pointer is on the first element echo current($array) . "<br />\n"; // "step one" // skip two steps next($array); next($array); echo current($array) . "<br />\n"; // "step three" // reset pointer, start again on step one reset($array); echo current($array) . "<br />\n"; // "step one" ?> ``` ### Notes > **Note**: The return value for an empty array is indistinguishable from the return value in case of an array which has a bool **`false`** first element. To properly check the value of the first element of an array which may contain **`false`** elements, first check the [count()](function.count) of the array, or check that [key()](function.key) is not **`null`**, after calling **reset()**. > > ### See Also * [current()](function.current) - Return the current element in an array * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor * [end()](function.end) - Set the internal pointer of an array to its last element * [next()](function.next) - Advance the internal pointer of an array * [prev()](function.prev) - Rewind the internal array pointer * [array\_key\_first()](function.array-key-first) - Gets the first key of an array php SoapFault::__construct SoapFault::\_\_construct ======================== (PHP 5, PHP 7, PHP 8) SoapFault::\_\_construct — SoapFault constructor ### Description public **SoapFault::\_\_construct**( array|string|null `$code`, string `$string`, ?string `$actor` = **`null`**, [mixed](language.types.declarations#language.types.declarations.mixed) `$details` = **`null`**, ?string `$name` = **`null`**, [mixed](language.types.declarations#language.types.declarations.mixed) `$headerFault` = **`null`** ) This class is used to send SOAP fault responses from the PHP handler. `faultcode`, `faultstring`, `faultactor` and `detail` are standard elements of a SOAP Fault. ### Parameters `faultcode` The error code of the [SoapFault](class.soapfault). `faultstring` The error message of the [SoapFault](class.soapfault). `faultactor` A string identifying the actor that caused the error. `detail` More details about the cause of the error. `faultname` Can be used to select the proper fault encoding from WSDL. `headerfault` Can be used during SOAP header handling to report an error in the response header. ### Examples **Example #1 Some examples** ``` <?php function test($x) {     return new SoapFault("Server", "Some error message"); } $server = new SoapServer(null, array('uri' => "http://test-uri/")); $server->addFunction("test"); $server->handle(); ?> ``` It is possible to use PHP exception mechanism to throw SOAP Fault. **Example #2 Some examples** ``` <?php function test($x) {     throw new SoapFault("Server", "Some error message"); } $server = new SoapServer(null, array('uri' => "http://test-uri/")); $server->addFunction("test"); $server->handle(); ?> ``` ### See Also * [SoapServer::fault()](soapserver.fault) - Issue SoapServer fault indicating an error * [is\_soap\_fault()](function.is-soap-fault) - Checks if a SOAP call has failed php The Yar_Client class The Yar\_Client class ===================== Introduction ------------ (No version information available, might only be in Git) Class synopsis -------------- class **Yar\_Client** { /\* Properties \*/ protected [$\_protocol](class.yar-client#yar-client.props.protocol); protected [$\_uri](class.yar-client#yar-client.props.uri); protected [$\_options](class.yar-client#yar-client.props.options); protected [$\_running](class.yar-client#yar-client.props.running); /\* Methods \*/ ``` public __call(string $method, array $parameters): void ``` ``` final public __construct(string $url, array $options = ?) ``` ``` public setOpt(int $name, mixed $value): Yar_Client|false ``` } Properties ---------- \_protocol \_uri \_options \_running Table of Contents ----------------- * [Yar\_Client::\_\_call](yar-client.call) — Call service * [Yar\_Client::\_\_construct](yar-client.construct) — Create a client * [Yar\_Client::setOpt](yar-client.setopt) — Set calling contexts php ReflectionFunctionAbstract::getClosureScopeClass ReflectionFunctionAbstract::getClosureScopeClass ================================================ (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getClosureScopeClass — Returns the scope associated to the closure ### Description ``` public ReflectionFunctionAbstract::getClosureScopeClass(): ?ReflectionClass ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns the class on success or **`null`** on failure. php sodium_crypto_pwhash_scryptsalsa208sha256_str sodium\_crypto\_pwhash\_scryptsalsa208sha256\_str ================================================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_pwhash\_scryptsalsa208sha256\_str — Get an ASCII encoded hash ### Description ``` sodium_crypto_pwhash_scryptsalsa208sha256_str(string $password, int $opslimit, int $memlimit): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `password` `opslimit` `memlimit` ### Return Values php SplFileInfo::isReadable SplFileInfo::isReadable ======================= (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::isReadable — Tells if file is readable ### Description ``` public SplFileInfo::isReadable(): bool ``` Check if the file is readable. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if readable, **`false`** otherwise. ### Examples **Example #1 **SplFileInfo::isReadable()** example** ``` <?php $info = new SplFileInfo(__FILE__); var_dump($info->isReadable()); $info = new SplFileInfo('foo'); var_dump($info->isReadable()); ?> ``` The above example will output something similar to: ``` bool(true) bool(false) ``` php RecursiveTreeIterator::getPostfix RecursiveTreeIterator::getPostfix ================================= (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::getPostfix — Get the postfix ### Description ``` public RecursiveTreeIterator::getPostfix(): string ``` Gets the string to place after the current element. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns the string to place after the current element. php Imagick::edgeImage Imagick::edgeImage ================== (PECL imagick 2, PECL imagick 3) Imagick::edgeImage — Enhance edges within the image ### Description ``` public Imagick::edgeImage(float $radius): bool ``` Enhance edges within the image with a convolution filter of the given radius. Use radius 0 and it will be auto-selected. ### Parameters `radius` The radius of the operation. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::edgeImage()**** ``` <?php function edgeImage($imagePath, $radius) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->edgeImage($radius);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php untaint untaint ======= (PECL taint >=0.1.0) untaint — Untaint strings ### Description ``` untaint(string &$string, string ...$strings): bool ``` Untaint strings ### Parameters `string` `strings` ### Return Values php addcslashes addcslashes =========== (PHP 4, PHP 5, PHP 7, PHP 8) addcslashes — Quote string with slashes in a C style ### Description ``` addcslashes(string $string, string $characters): string ``` Returns a string with backslashes before characters that are listed in `characters` parameter. ### Parameters `string` The string to be escaped. `characters` A list of characters to be escaped. If `characters` contains characters `\n`, `\r` etc., they are converted in C-like style, while other non-alphanumeric characters with ASCII codes lower than 32 and higher than 126 converted to octal representation. When you define a sequence of characters in the `characters` argument make sure that you know what characters come between the characters that you set as the start and end of the range. ``` <?php echo addcslashes('foo[ ]', 'A..z'); // output:  \f\o\o\[ \] // All upper and lower-case letters will be escaped // ... but so will the [\]^_` ?> ``` Also, if the first character in a range has a higher ASCII value than the second character in the range, no range will be constructed. Only the start, end and period characters will be escaped. Use the [ord()](function.ord) function to find the ASCII value for a character. ``` <?php echo addcslashes("zoo['.']", 'z..A'); // output:  \zoo['\.'] ?> ``` Be careful if you choose to escape characters 0, a, b, f, n, r, t and v. They will be converted to \0, \a, \b, \f, \n, \r, \t and \v, all of which are predefined escape sequences in C. Many of these sequences are also defined in other C-derived languages, including PHP, meaning that you may not get the desired result if you use the output of **addcslashes()** to generate code in those languages with these characters defined in `characters`. ### Return Values Returns the escaped string. ### Examples `characters` like "\0..\37", which would escape all characters with ASCII code between 0 and 31. **Example #1 **addcslashes()** example** ``` <?php $escaped = addcslashes($not_escaped, "\0..\37!@\177..\377"); ?> ``` ### See Also * [stripcslashes()](function.stripcslashes) - Un-quote string quoted with addcslashes * [stripslashes()](function.stripslashes) - Un-quotes a quoted string * [addslashes()](function.addslashes) - Quote string with slashes * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities * [quotemeta()](function.quotemeta) - Quote meta characters php mysqli::$host_info mysqli::$host\_info =================== mysqli\_get\_host\_info ======================= (PHP 5, PHP 7, PHP 8) mysqli::$host\_info -- mysqli\_get\_host\_info — Returns a string representing the type of connection used ### Description Object-oriented style string [$mysqli->host\_info](mysqli.get-host-info); Procedural style ``` mysqli_get_host_info(mysqli $mysql): string ``` Returns a string describing the connection represented by the `mysql` parameter (including the server host name). ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) ### Return Values A character string representing the server hostname and the connection type. ### Examples **Example #1 $mysqli->host\_info example** Object-oriented style ``` <?php $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print host information */ printf("Host info: %s\n", $mysqli->host_info); /* close connection */ $mysqli->close(); ?> ``` Procedural style ``` <?php $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* check connection */ if (mysqli_connect_errno()) {     printf("Connect failed: %s\n", mysqli_connect_error());     exit(); } /* print host information */ printf("Host info: %s\n", mysqli_get_host_info($link)); /* close connection */ mysqli_close($link); ?> ``` The above examples will output: ``` Host info: Localhost via UNIX socket ``` ### See Also * [mysqli\_get\_proto\_info()](mysqli.get-proto-info) - Returns the version of the MySQL protocol used
programming_docs
php The SolrGenericResponse class The SolrGenericResponse class ============================= Introduction ------------ (PECL solr >= 0.9.2) Represents a response from the solr server. Class synopsis -------------- final class **SolrGenericResponse** extends [SolrResponse](class.solrresponse) { /\* Constants \*/ const int [PARSE\_SOLR\_OBJ](class.solrgenericresponse#solrgenericresponse.constants.parse-solr-obj) = 0; const int [PARSE\_SOLR\_DOC](class.solrgenericresponse#solrgenericresponse.constants.parse-solr-doc) = 1; /\* Inherited properties \*/ const int [SolrResponse::PARSE\_SOLR\_OBJ](class.solrresponse#solrresponse.constants.parse-solr-obj) = 0; const int [SolrResponse::PARSE\_SOLR\_DOC](class.solrresponse#solrresponse.constants.parse-solr-doc) = 1; protected int [$http\_status](class.solrresponse#solrresponse.props.http-status); protected int [$parser\_mode](class.solrresponse#solrresponse.props.parser-mode); protected bool [$success](class.solrresponse#solrresponse.props.success); protected string [$http\_status\_message](class.solrresponse#solrresponse.props.http-status-message); protected string [$http\_request\_url](class.solrresponse#solrresponse.props.http-request-url); protected string [$http\_raw\_request\_headers](class.solrresponse#solrresponse.props.http-raw-request-headers); protected string [$http\_raw\_request](class.solrresponse#solrresponse.props.http-raw-request); protected string [$http\_raw\_response\_headers](class.solrresponse#solrresponse.props.http-raw-response-headers); protected string [$http\_raw\_response](class.solrresponse#solrresponse.props.http-raw-response); protected string [$http\_digested\_response](class.solrresponse#solrresponse.props.http-digested-response); /\* Methods \*/ public [\_\_construct](solrgenericresponse.construct)() public [\_\_destruct](solrgenericresponse.destruct)() /\* Inherited methods \*/ ``` public SolrResponse::getDigestedResponse(): string ``` ``` public SolrResponse::getHttpStatus(): int ``` ``` public SolrResponse::getHttpStatusMessage(): string ``` ``` public SolrResponse::getRawRequest(): string ``` ``` public SolrResponse::getRawRequestHeaders(): string ``` ``` public SolrResponse::getRawResponse(): string ``` ``` public SolrResponse::getRawResponseHeaders(): string ``` ``` public SolrResponse::getRequestUrl(): string ``` ``` public SolrResponse::getResponse(): SolrObject ``` ``` public SolrResponse::setParseMode(int $parser_mode = 0): bool ``` ``` public SolrResponse::success(): bool ``` } Predefined Constants -------------------- SolrGenericResponse Class constants ----------------------------------- **`SolrGenericResponse::PARSE_SOLR_OBJ`** Documents should be parsed as SolrObject instances **`SolrGenericResponse::PARSE_SOLR_DOC`** Documents should be parsed as SolrDocument instances. Table of Contents ----------------- * [SolrGenericResponse::\_\_construct](solrgenericresponse.construct) — Constructor * [SolrGenericResponse::\_\_destruct](solrgenericresponse.destruct) — Destructor php ReflectionZendExtension::__construct ReflectionZendExtension::\_\_construct ====================================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionZendExtension::\_\_construct — Constructor ### Description public **ReflectionZendExtension::\_\_construct**(string `$name`) **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php Imagick::setImagePage Imagick::setImagePage ===================== (PECL imagick 2, PECL imagick 3) Imagick::setImagePage — Sets the page geometry of the image ### Description ``` public Imagick::setImagePage( int $width, int $height, int $x, int $y ): bool ``` Sets the page geometry of the image. ### Parameters `width` `height` `x` `y` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. php class_implements class\_implements ================= (PHP 5, PHP 7, PHP 8) class\_implements — Return the interfaces which are implemented by the given class or interface ### Description ``` class_implements(object|string $object_or_class, bool $autoload = true): array|false ``` This function returns an array with the names of the interfaces that the given `object_or_class` and its parents implement. ### Parameters `object_or_class` An object (class instance) or a string (class or interface name). `autoload` Whether to call [\_\_autoload](language.oop5.autoload) by default. ### Return Values An array on success, or **`false`** when the given class doesn't exist. ### Examples **Example #1 **class\_implements()** example** ``` <?php interface foo { } class bar implements foo {} print_r(class_implements(new bar)); // you may also specify the parameter as a string print_r(class_implements('bar')); spl_autoload_register(); // use autoloading to load the 'not_loaded' class print_r(class_implements('not_loaded', true)); ?> ``` The above example will output something similar to: ``` Array ( [foo] => foo ) Array ( [foo] => foo ) Array ( [interface_of_not_loaded] => interface_of_not_loaded ) ``` ### See Also * [class\_parents()](function.class-parents) - Return the parent classes of the given class * [get\_declared\_interfaces()](function.get-declared-interfaces) - Returns an array of all declared interfaces php ReflectionParameter::getDeclaringFunction ReflectionParameter::getDeclaringFunction ========================================= (PHP 5 >= 5.1.3, PHP 7, PHP 8) ReflectionParameter::getDeclaringFunction — Gets declaring function ### Description ``` public ReflectionParameter::getDeclaringFunction(): ReflectionFunctionAbstract ``` Gets the declaring function. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values A [ReflectionFunction](class.reflectionfunction) object. ### See Also * [ReflectionParameter::getDeclaringClass()](reflectionparameter.getdeclaringclass) - Gets declaring class php wincache_lock wincache\_lock ============== (PECL wincache >= 1.1.0) wincache\_lock — Acquires an exclusive lock on a given key ### Description ``` wincache_lock(string $key, bool $isglobal = false): bool ``` Obtains an exclusive lock on a given key. The execution of the current script will be blocked until the lock can be obtained. Once the lock is obtained, the other scripts that try to request the lock by using the same key will be blocked, until the current script releases the lock by using [wincache\_unlock()](function.wincache-unlock). **Warning** Using of the **wincache\_lock()** and [wincache\_unlock()](function.wincache-unlock) can cause deadlocks when executing PHP scripts in a multi-process environment like FastCGI. Do not use these functions unless you are absolutely sure you need to use them. For the majority of the operations on the user cache it is not necessary to use these functions. ### Parameters `key` Name of the key in the cache to get the lock on. `isglobal` Controls whether the scope of the lock is system-wide or local. Local locks are scoped to the application pool in IIS FastCGI case or to all php processes that have the same parent process identifier. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Using **wincache\_lock()**** ``` <?php $fp = fopen("/tmp/lock.txt", "r+"); if (wincache_lock(“lock_txt_lock”)) { // do an exclusive lock     ftruncate($fp, 0); // truncate file     fwrite($fp, "Write something here\n");     wincache_unlock(“lock_txt_lock”); // release the lock } else {     echo "Couldn't get the lock!"; } fclose($fp); ?> ``` ### See Also * [wincache\_unlock()](function.wincache-unlock) - Releases an exclusive lock on a given key * [wincache\_ucache\_set()](function.wincache-ucache-set) - Adds a variable in user cache and overwrites a variable if it already exists in the cache * [wincache\_ucache\_get()](function.wincache-ucache-get) - Gets a variable stored in the user cache * [wincache\_ucache\_delete()](function.wincache-ucache-delete) - Deletes variables from the user cache * [wincache\_ucache\_clear()](function.wincache-ucache-clear) - Deletes entire content of the user cache * [wincache\_ucache\_exists()](function.wincache-ucache-exists) - Checks if a variable exists in the user cache * [wincache\_ucache\_meminfo()](function.wincache-ucache-meminfo) - Retrieves information about user cache memory usage * [wincache\_ucache\_info()](function.wincache-ucache-info) - Retrieves information about data stored in the user cache * [wincache\_scache\_info()](function.wincache-scache-info) - Retrieves information about files cached in the session cache php EvWatcher::invoke EvWatcher::invoke ================= (PECL ev >= 0.2.0) EvWatcher::invoke — Invokes the watcher callback with the given received events bit mask ### Description ``` public EvWatcher::invoke( int $revents ): void ``` Invokes the watcher callback with the given received events bit mask. ### Parameters `revents` Bit mask of watcher [received events](class.ev#ev.constants.watcher-revents) . ### Return Values No value is returned. php fileatime fileatime ========= (PHP 4, PHP 5, PHP 7, PHP 8) fileatime — Gets last access time of file ### Description ``` fileatime(string $filename): int|false ``` Gets the last access time of the given file. ### Parameters `filename` Path to the file. ### Return Values Returns the time the file was last accessed, or **`false`** on failure. The time is returned as a Unix timestamp. ### Errors/Exceptions Upon failure, an **`E_WARNING`** is emitted. ### Examples **Example #1 **fileatime()** example** ``` <?php // outputs e.g.  somefile.txt was last accessed: December 29 2002 22:16:23. $filename = 'somefile.txt'; if (file_exists($filename)) {     echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename)); } ?> ``` ### Notes > > **Note**: > > > The atime of a file is supposed to change whenever the data blocks of a file are being read. This can be costly performance-wise when an application regularly accesses a very large number of files or directories. > > Some Unix filesystems can be mounted with atime updates disabled to increase the performance of such applications; USENET news spools are a common example. On such filesystems this function will be useless. > > > > **Note**: > > > Note that time resolution may differ from one file system to another. > > > > **Note**: The results of this function are cached. See [clearstatcache()](function.clearstatcache) for more details. > > **Tip**As of PHP 5.0.0, this function can also be used with *some* URL wrappers. Refer to [Supported Protocols and Wrappers](https://www.php.net/manual/en/wrappers.php) to determine which wrappers support [stat()](function.stat) family of functionality. ### See Also * [filemtime()](function.filemtime) - Gets file modification time * [fileinode()](function.fileinode) - Gets file inode * [date()](function.date) - Format a Unix timestamp php ReflectionClassConstant::export ReflectionClassConstant::export =============================== (PHP 7 >= 7.1.0) ReflectionClassConstant::export — Export **Warning**This function has been *DEPRECATED* as of PHP 7.4.0, and *REMOVED* as of PHP 8.0.0. Relying on this function is highly discouraged. ### Description ``` public static ReflectionClassConstant::export(mixed $class, string $name, bool $return = ?): string ``` Exports a reflection. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `class` The reflection to export. `name` The class constant name. `return` Setting to **`true`** will return the export, as opposed to emitting it. Setting to **`false`** (the default) will do the opposite. ### Return Values ### See Also * [ReflectionClassConstant::\_\_toString()](reflectionclassconstant.tostring) - Returns the string representation of the ReflectionClassConstant object php pcntl_wstopsig pcntl\_wstopsig =============== (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) pcntl\_wstopsig — Returns the signal which caused the child to stop ### Description ``` pcntl_wstopsig(int $status): int|false ``` Returns the number of the signal which caused the child to stop. This function is only useful if [pcntl\_wifstopped()](function.pcntl-wifstopped) returned **`true`**. ### Parameters `status` The `status` parameter is the status parameter supplied to a successful call to [pcntl\_waitpid()](function.pcntl-waitpid). ### Return Values Returns the signal number. If the functionality is not supported by the OS, **`false`** is returned. ### See Also * [pcntl\_waitpid()](function.pcntl-waitpid) - Waits on or returns the status of a forked child * [pcntl\_wifstopped()](function.pcntl-wifstopped) - Checks whether the child process is currently stopped php DateTime::setTime DateTime::setTime ================= date\_time\_set =============== (PHP 5 >= 5.2.0, PHP 7, PHP 8) DateTime::setTime -- date\_time\_set — Sets the time ### Description Object-oriented style ``` public DateTime::setTime( int $hour, int $minute, int $second = 0, int $microsecond = 0 ): DateTime ``` Procedural style ``` date_time_set( DateTime $object, int $hour, int $minute, int $second = 0, int $microsecond = 0 ): DateTime ``` Resets the current time of the DateTime object to a different time. Like [DateTimeImmutable::setTime()](datetimeimmutable.settime) but works with [DateTime](class.datetime). The procedural version takes the [DateTime](class.datetime) object as its first argument. ### Parameters `object` Procedural style only: A [DateTime](class.datetime) object returned by [date\_create()](function.date-create). The function modifies this object. `hour` Hour of the time. `minute` Minute of the time. `second` Second of the time. `microsecond` Microsecond of the time. ### Return Values Returns the modified [DateTime](class.datetime) object for method chaining. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The behaviour with double existing hours (during the fall-back DST transition) changed. Previously PHP would pick the second occurrence (after the DST transition), instead of the first occurrence (before DST transition). | | 7.1.0 | The `microsecond` parameter was added. | ### See Also * [DateTimeImmutable::setTime()](datetimeimmutable.settime) - Sets the time php The Yaf_Session class The Yaf\_Session class ====================== Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Session** implements [Iterator](class.iterator), [ArrayAccess](class.arrayaccess), [Countable](class.countable) { /\* Properties \*/ protected static [$\_instance](class.yaf-session#yaf-session.props.instance); protected [$\_session](class.yaf-session#yaf-session.props.session); protected [$\_started](class.yaf-session#yaf-session.props.started); /\* Methods \*/ private [\_\_construct](yaf-session.construct)() ``` public count(): void ``` ``` public current(): void ``` ``` public del(string $name): void ``` ``` public __get(string $name): void ``` ``` public static getInstance(): void ``` ``` public has(string $name): void ``` ``` public __isset(string $name): void ``` ``` public key(): void ``` ``` public next(): void ``` ``` public offsetExists(string $name): void ``` ``` public offsetGet(string $name): void ``` ``` public offsetSet(string $name, string $value): void ``` ``` public offsetUnset(string $name): void ``` ``` public rewind(): void ``` ``` public __set(string $name, string $value): void ``` ``` public start(): void ``` ``` public __unset(string $name): void ``` ``` public valid(): void ``` } Properties ---------- \_instance \_session \_started Table of Contents ----------------- * [Yaf\_Session::\_\_construct](yaf-session.construct) — Constructor of Yaf\_Session * [Yaf\_Session::count](yaf-session.count) — The count purpose * [Yaf\_Session::current](yaf-session.current) — The current purpose * [Yaf\_Session::del](yaf-session.del) — The del purpose * [Yaf\_Session::\_\_get](yaf-session.get) — The \_\_get purpose * [Yaf\_Session::getInstance](yaf-session.getinstance) — The getInstance purpose * [Yaf\_Session::has](yaf-session.has) — The has purpose * [Yaf\_Session::\_\_isset](yaf-session.isset) — The \_\_isset purpose * [Yaf\_Session::key](yaf-session.key) — The key purpose * [Yaf\_Session::next](yaf-session.next) — The next purpose * [Yaf\_Session::offsetExists](yaf-session.offsetexists) — The offsetExists purpose * [Yaf\_Session::offsetGet](yaf-session.offsetget) — The offsetGet purpose * [Yaf\_Session::offsetSet](yaf-session.offsetset) — The offsetSet purpose * [Yaf\_Session::offsetUnset](yaf-session.offsetunset) — The offsetUnset purpose * [Yaf\_Session::rewind](yaf-session.rewind) — The rewind purpose * [Yaf\_Session::\_\_set](yaf-session.set) — The \_\_set purpose * [Yaf\_Session::start](yaf-session.start) — The start purpose * [Yaf\_Session::\_\_unset](yaf-session.unset) — The \_\_unset purpose * [Yaf\_Session::valid](yaf-session.valid) — The valid purpose php None Using namespaces: Basics ------------------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) Before discussing the use of namespaces, it is important to understand how PHP knows which namespaced element your code is requesting. A simple analogy can be made between PHP namespaces and a filesystem. There are three ways to access a file in a file system: 1. Relative file name like `foo.txt`. This resolves to `currentdirectory/foo.txt` where currentdirectory is the directory currently occupied. So if the current directory is `/home/foo`, the name resolves to `/home/foo/foo.txt`. 2. Relative path name like `subdirectory/foo.txt`. This resolves to `currentdirectory/subdirectory/foo.txt`. 3. Absolute path name like `/main/foo.txt`. This resolves to `/main/foo.txt`. The same principle can be applied to namespaced elements in PHP. For example, a class name can be referred to in three ways: 1. Unqualified name, or an unprefixed class name like `$a = new foo();` or `foo::staticmethod();`. If the current namespace is `currentnamespace`, this resolves to `currentnamespace\foo`. If the code is global, non-namespaced code, this resolves to `foo`. One caveat: unqualified names for functions and constants will resolve to global functions and constants if the namespaced function or constant is not defined. See [Using namespaces: fallback to global function/constant](language.namespaces.fallback) for details. 2. Qualified name, or a prefixed class name like `$a = new subnamespace\foo();` or `subnamespace\foo::staticmethod();`. If the current namespace is `currentnamespace`, this resolves to `currentnamespace\subnamespace\foo`. If the code is global, non-namespaced code, this resolves to `subnamespace\foo`. 3. Fully qualified name, or a prefixed name with global prefix operator like `$a = new \currentnamespace\foo();` or `\currentnamespace\foo::staticmethod();`. This always resolves to the literal name specified in the code, `currentnamespace\foo`. Here is an example of the three kinds of syntax in actual code: file1.php ``` <?php namespace Foo\Bar\subnamespace; const FOO = 1; function foo() {} class foo {     static function staticmethod() {} } ?> ``` file2.php ``` <?php namespace Foo\Bar; include 'file1.php'; const FOO = 2; function foo() {} class foo {     static function staticmethod() {} } /* Unqualified name */ foo(); // resolves to function Foo\Bar\foo foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod echo FOO; // resolves to constant Foo\Bar\FOO /* Qualified name */ subnamespace\foo(); // resolves to function Foo\Bar\subnamespace\foo subnamespace\foo::staticmethod(); // resolves to class Foo\Bar\subnamespace\foo,                                   // method staticmethod echo subnamespace\FOO; // resolves to constant Foo\Bar\subnamespace\FOO                                    /* Fully qualified name */ \Foo\Bar\foo(); // resolves to function Foo\Bar\foo \Foo\Bar\foo::staticmethod(); // resolves to class Foo\Bar\foo, method staticmethod echo \Foo\Bar\FOO; // resolves to constant Foo\Bar\FOO ?> ``` Note that to access any global class, function or constant, a fully qualified name can be used, such as **\strlen()** or **\Exception** or `\INI_ALL`. **Example #1 Accessing global classes, functions and constants from within a namespace** ``` <?php namespace Foo; function strlen() {} const INI_ALL = 3; class Exception {} $a = \strlen('hi'); // calls global function strlen $b = \INI_ALL; // accesses global constant INI_ALL $c = new \Exception('error'); // instantiates global class Exception ?> ```
programming_docs
php SplFileInfo::getCTime SplFileInfo::getCTime ===================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getCTime — Gets the inode change time ### Description ``` public SplFileInfo::getCTime(): int|false ``` Returns the inode change time for the file. The time returned is a Unix timestamp. ### Parameters This function has no parameters. ### Return Values The last change time, in a Unix timestamp on success, or **`false`** on failure. ### Errors/Exceptions Throws [RunTimeException](class.runtimeexception) on error. ### Examples **Example #1 **SplFileInfo::getCTime()** example** ``` <?php $info = new SplFileInfo(__FILE__); echo 'Last changed at ' . date('g:i a', $info->getCTime()); ?> ``` The above example will output something similar to: ``` Last changed at 1:49 pm ``` ### See Also * [filectime()](function.filectime) - Gets inode change time of file php pg_parameter_status pg\_parameter\_status ===================== (PHP 5, PHP 7, PHP 8) pg\_parameter\_status — Looks up a current parameter setting of the server ### Description ``` pg_parameter_status(PgSql\Connection $connection = ?, string $param_name): string ``` Looks up a current parameter setting of the server. Certain parameter values are reported by the server automatically at connection startup or whenever their values change. **pg\_parameter\_status()** can be used to interrogate these settings. It returns the current value of a parameter if known, or **`false`** if the parameter is not known. Parameters reported as of PostgreSQL 8.0 include `server_version`, `server_encoding`, `client_encoding`, `is_superuser`, `session_authorization`, `DateStyle`, `TimeZone`, and `integer_datetimes`. (`server_encoding`, `TimeZone`, and `integer_datetimes` were not reported by releases before 8.0.) Note that `server_version`, `server_encoding` and `integer_datetimes` cannot change after PostgreSQL startup. PostgreSQL 7.3 or lower servers do not report parameter settings, **pg\_parameter\_status()** includes logic to obtain values for `server_version` and `client_encoding` anyway. Applications are encouraged to use **pg\_parameter\_status()** rather than ad hoc code to determine these values. **Caution** On a pre-7.4 PostgreSQL server, changing `client_encoding` via `SET` after connection startup will not be reflected by **pg\_parameter\_status()**. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `param_name` Possible `param_name` values include `server_version`, `server_encoding`, `client_encoding`, `is_superuser`, `session_authorization`, `DateStyle`, `TimeZone`, and `integer_datetimes`. Note that this value is case-sensitive. ### Return Values A string containing the value of the parameter, **`false`** on failure or invalid `param_name`. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_parameter\_status()** example** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   echo "Server encoding: ", pg_parameter_status($dbconn, "server_encoding"); ?> ``` The above example will output: ``` Server encoding: SQL_ASCII ``` php ImagickDraw::translate ImagickDraw::translate ====================== (PECL imagick 2, PECL imagick 3) ImagickDraw::translate — Applies a translation to the current coordinate system ### Description ``` public ImagickDraw::translate(float $x, float $y): bool ``` **Warning**This function is currently not documented; only its argument list is available. Applies a translation to the current coordinate system which moves the coordinate system origin to the specified coordinate. ### Parameters `x` horizontal translation `y` vertical translation ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::translate()** example** ``` <?php function translate($strokeColor, $fillColor, $backgroundColor, $fillModifiedColor,                     $startX, $startY, $endX, $endY, $translateX, $translateY) {     $draw = new \ImagickDraw();     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->rectangle($startX, $startY, $endX, $endY);     $draw->setFillColor($fillModifiedColor);     $draw->translate($translateX, $translateY);     $draw->rectangle($startX, $startY, $endX, $endY);     $image = new \Imagick();     $image->newImage(500, 500, $backgroundColor);     $image->setImageFormat("png");     $image->drawImage($draw);     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php uopz_redefine uopz\_redefine ============== (PECL uopz 1, PECL uopz 2, PECL uopz 5, PECL uopz 6, PECL uopz 7) uopz\_redefine — Redefine a constant ### Description ``` uopz_redefine(string $constant, mixed $value): bool ``` ``` uopz_redefine(string $class, string $constant, mixed $value): bool ``` Redefines the given `constant` as `value` ### Parameters `class` The name of the class containing the constant `constant` The name of the constant `value` The new value for the constant, must be a valid type for a constant variable ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **uopz\_redefine()** example** ``` <?php define("MY", 100); uopz_redefine("MY", 1000); echo MY; ?> ``` The above example will output: ``` 1000 ``` php SoapClient::__getFunctions SoapClient::\_\_getFunctions ============================ (PHP 5, PHP 7, PHP 8) SoapClient::\_\_getFunctions — Returns list of available SOAP functions ### Description ``` public SoapClient::__getFunctions(): ?array ``` Returns an array of functions described in the WSDL for the Web service. > > **Note**: > > > This function only works in WSDL mode. > > > ### Parameters This function has no parameters. ### Return Values The array of SOAP function prototypes, detailing the return type, the function name and parameter types. ### Examples **Example #1 **SoapClient::\_\_getFunctions()** example** ``` <?php $client = new SoapClient('http://soap.amazon.com/schemas3/AmazonWebServices.wsdl'); var_dump($client->__getFunctions()); ?> ``` The above example will output: ``` array(26) { [0]=> string(70) "ProductInfo KeywordSearchRequest(KeywordRequest $KeywordSearchRequest)" [1]=> string(79) "ProductInfo TextStreamSearchRequest(TextStreamRequest $TextStreamSearchRequest)" [2]=> string(64) "ProductInfo PowerSearchRequest(PowerRequest $PowerSearchRequest)" ... [23]=> string(107) "ShoppingCart RemoveShoppingCartItemsRequest(RemoveShoppingCartItemsRequest $RemoveShoppingCartItemsRequest)" [24]=> string(107) "ShoppingCart ModifyShoppingCartItemsRequest(ModifyShoppingCartItemsRequest $ModifyShoppingCartItemsRequest)" [25]=> string(118) "GetTransactionDetailsResponse GetTransactionDetailsRequest(GetTransactionDetailsRequest $GetTransactionDetailsRequest)" } ``` ### See Also * [SoapClient::\_\_construct()](soapclient.construct) - SoapClient constructor php Parle\RParser::trace Parle\RParser::trace ==================== (PECL parle >= 0.7.0) Parle\RParser::trace — Trace the parser operation ### Description ``` public Parle\RParser::trace(): string ``` Retrieve the current parser operation description. This can be especially useful to study the parser and to optimize the grammar. ### Parameters This function has no parameters. ### Return Values Returns a string with the trace information. php EventConfig::setMaxDispatchInterval EventConfig::setMaxDispatchInterval =================================== (PECL event >= 2.1.0-alpha) EventConfig::setMaxDispatchInterval — Prevents priority inversion ### Description ``` public EventConfig::setMaxDispatchInterval( int $max_interval , int $max_callbacks , int $min_priority ): void ``` Prevents priority inversion by limiting how many low-priority event callbacks can be invoked before checking for more high-priority events. > > **Note**: > > > Available since `libevent 2.1.0-alpha` . > > ### Parameters `max_interval` An interval after which Libevent should stop running callbacks and check for more events, or **`0`** , if there should be no such interval. `max_callbacks` A number of callbacks after which Libevent should stop running callbacks and check for more events, or **`-1`** , if there should be no such limit. `min_priority` A priority below which `max_interval` and `max_callbacks` should not be enforced. If this is set to **`0`** , they are enforced for events of every priority; if it's set to **`1`** , they're enforced for events of priority **`1`** and above, and so on. ### Return Values Returns **`true`** on success or **`false`** on failure. php fdf_set_ap fdf\_set\_ap ============ (PHP 4, PHP 5 < 5.3.0, PECL fdf SVN) fdf\_set\_ap — Set the appearance of a field ### Description ``` fdf_set_ap( resource $fdf_document, string $field_name, int $face, string $filename, int $page_number ): bool ``` Sets the appearance of a field (i.e. the value of the `/AP` key). ### Parameters `fdf_document` The FDF document handle, returned by [fdf\_create()](function.fdf-create), [fdf\_open()](function.fdf-open) or [fdf\_open\_string()](function.fdf-open-string). `field_name` `face` The possible values **`FDFNormalAP`**, **`FDFRolloverAP`** and **`FDFDownAP`**. `filename` `page_number` ### Return Values Returns **`true`** on success or **`false`** on failure. php mysqli::prepare mysqli::prepare =============== mysqli\_prepare =============== (PHP 5, PHP 7, PHP 8) mysqli::prepare -- mysqli\_prepare — Prepares an SQL statement for execution ### Description Object-oriented style ``` public mysqli::prepare(string $query): mysqli_stmt|false ``` Procedural style ``` mysqli_prepare(mysqli $mysql, string $query): mysqli_stmt|false ``` Prepares the SQL query, and returns a statement handle to be used for further operations on the statement. The query must consist of a single SQL statement. The statement template can contain zero or more question mark (`?`) parameter markers⁠—also called placeholders. The parameter markers must be bound to application variables using [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) before executing the statement. ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `query` The query, as a string. It must consist of a single SQL statement. The SQL statement may contain zero or more parameter markers represented by question mark (`?`) characters at the appropriate positions. > > **Note**: > > > The markers are legal only in certain places in SQL statements. For example, they are permitted in the `VALUES()` list of an `INSERT` statement (to specify column values for a row), or in a comparison with a column in a `WHERE` clause to specify a comparison value. However, they are not permitted for identifiers (such as table or column names). > > ### Return Values **mysqli\_prepare()** returns a statement object or **`false`** if an error occurred. ### Examples **Example #1 **mysqli::prepare()** example** Object-oriented style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); $city = "Amersfoort"; /* create a prepared statement */ $stmt = $mysqli->prepare("SELECT District FROM City WHERE Name=?"); /* bind parameters for markers */ $stmt->bind_param("s", $city); /* execute query */ $stmt->execute(); /* bind result variables */ $stmt->bind_result($district); /* fetch value */ $stmt->fetch(); printf("%s is in district %s\n", $city, $district); ``` Procedural style ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); $city = "Amersfoort"; /* create a prepared statement */ $stmt = mysqli_prepare($link, "SELECT District FROM City WHERE Name=?"); /* bind parameters for markers */ mysqli_stmt_bind_param($stmt, "s", $city); /* execute query */ mysqli_stmt_execute($stmt); /* bind result variables */ mysqli_stmt_bind_result($stmt, $district); /* fetch value */ mysqli_stmt_fetch($stmt); printf("%s is in district %s\n", $city, $district); ``` The above examples will output: ``` Amersfoort is in district Utrecht ``` ### See Also * [mysqli\_stmt\_execute()](mysqli-stmt.execute) - Executes a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables * [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) - Binds variables to a prepared statement as parameters * [mysqli\_stmt\_bind\_result()](mysqli-stmt.bind-result) - Binds variables to a prepared statement for result storage * [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) - Gets a result set from a prepared statement as a mysqli\_result object * [mysqli\_stmt\_close()](mysqli-stmt.close) - Closes a prepared statement php SolrInputDocument::addChildDocument SolrInputDocument::addChildDocument =================================== (PECL solr >= 2.3.0) SolrInputDocument::addChildDocument — Adds a child document for block indexing ### Description ``` public SolrInputDocument::addChildDocument(SolrInputDocument $child): void ``` Adds a child document to construct a document block with nested documents. ### Parameters `child` A [SolrInputDocument](class.solrinputdocument) object. ### Return Values No value is returned. ### Errors/Exceptions Throws [SolrIllegalArgumentException](class.solrillegalargumentexception) on failure. Throws [SolrException](class.solrexception) on internal failure. ### Examples **Example #1 **SolrInputDocument::addChildDocument()** example** ``` <?php include "bootstrap.php"; $options = array (     'hostname' => SOLR_SERVER_HOSTNAME,     'login'    => SOLR_SERVER_USERNAME,     'password' => SOLR_SERVER_PASSWORD,     'port'     => SOLR_SERVER_PORT,     'path'     => SOLR_SERVER_STORE_PATH, ); $client = new SolrClient($options); $product = new SolrInputDocument(); $product->addField('id', 'P-BLACK'); $product->addField('cat', 'tshirt'); $product->addField('cat', 'polo'); $product->addField('content_type', 'product'); $small = new SolrInputDocument(); $small->addField('id', 'TS-BLK-S'); $small->addField('content_type', 'sku'); $small->addField('size', 'S'); $small->addField('inventory', 100); $medium = new SolrInputDocument(); $medium->addField('id', 'TS-BLK-M'); $medium->addField('content_type', 'sku'); $medium->addField('size', 'M'); $medium->addField('inventory', 200); $large = new SolrInputDocument(); $large->addField('id', 'TS-BLK-L'); $large->addField('content_type', 'sku'); $large->addField('size', 'L'); $large->addField('inventory', 300); // add child documents  $product->addChildDocument($small); $product->addChildDocument($medium); $product->addChildDocument($large); // add product document block to the index $updateResponse = $client->addDocument(         $product,         true, // overwrite if the document exists         10000 // commit within 10 seconds ); print_r($updateResponse->getResponse()); ``` The above example will output something similar to: ``` SolrObject Object ( [responseHeader] => SolrObject Object ( [status] => 0 [QTime] => 5 ) ) ``` ### See Also * [SolrInputDocument::addChildDocuments()](solrinputdocument.addchilddocuments) - Adds an array of child documents * [SolrInputDocument::hasChildDocuments()](solrinputdocument.haschilddocuments) - Returns true if the document has any child documents * [SolrInputDocument::getChildDocuments()](solrinputdocument.getchilddocuments) - Returns an array of child documents (SolrInputDocument) * [SolrInputDocument::getChildDocumentsCount()](solrinputdocument.getchilddocumentscount) - Returns the number of child documents php mysqli::thread_safe mysqli::thread\_safe ==================== mysqli\_thread\_safe ==================== (PHP 5, PHP 7, PHP 8) mysqli::thread\_safe -- mysqli\_thread\_safe — Returns whether thread safety is given or not ### Description Object-oriented style ``` public mysqli::thread_safe(): bool ``` Procedural style ``` mysqli_thread_safe(): bool ``` Tells whether the client library is compiled as thread-safe. ### Parameters This function has no parameters. ### Return Values **`true`** if the client library is thread-safe, otherwise **`false`**. php pg_free_result pg\_free\_result ================ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_free\_result — Free result memory ### Description ``` pg_free_result(PgSql\Result $result): bool ``` **pg\_free\_result()** frees the memory and data associated with the specified [PgSql\Result](class.pgsql-result) instance. This function need only be called if memory consumption during script execution is a problem. Otherwise, all result memory will be automatically freed when the script ends. > > **Note**: > > > This function used to be called **pg\_freeresult()**. > > ### Parameters `result` An [PgSql\Result](class.pgsql-result) instance, returned by [pg\_query()](function.pg-query), [pg\_query\_params()](function.pg-query-params) or [pg\_execute()](function.pg-execute)(among others). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `result` parameter expects an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_free\_result()** example** ``` <?php $db = pg_connect("dbname=users user=me") || die(); $res = pg_query($db, "SELECT 1 UNION ALL SELECT 2"); $val = pg_fetch_result($res, 1, 0); echo "First field in the second row is: ", $val, "\n"; pg_free_result($res); ?> ``` The above example will output: ``` First field in the second row is: 2 ``` ### See Also * [pg\_query()](function.pg-query) - Execute a query * [pg\_query\_params()](function.pg-query-params) - Submits a command to the server and waits for the result, with the ability to pass parameters separately from the SQL command text * [pg\_execute()](function.pg-execute) - Sends a request to execute a prepared statement with given parameters, and waits for the result php Yaf_Session::rewind Yaf\_Session::rewind ==================== (Yaf >=1.0.0) Yaf\_Session::rewind — The rewind purpose ### Description ``` public Yaf_Session::rewind(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php Imagick::setSize Imagick::setSize ================ (PECL imagick 2, PECL imagick 3) Imagick::setSize — Sets the size of the Imagick object ### Description ``` public Imagick::setSize(int $columns, int $rows): bool ``` Sets the size of the Imagick object. Set it before you read a raw image format such as RGB, GRAY, or CMYK. ### Parameters `columns` `rows` ### Return Values Returns **`true`** on success.
programming_docs
php Collator::setAttribute Collator::setAttribute ====================== collator\_set\_attribute ======================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) Collator::setAttribute -- collator\_set\_attribute — Set collation attribute ### Description Object-oriented style ``` public Collator::setAttribute(int $attribute, int $value): bool ``` Procedural style ``` collator_set_attribute(Collator $object, int $attribute, int $value): bool ``` ### Parameters `object` [Collator](class.collator) object. `attribute` Attribute. `value` Attribute value. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **collator\_set\_attribute()** example** ``` <?php $coll = collator_create( 'en_CA' ); $val  = collator_get_attribute( $coll, Collator::NUMERIC_COLLATION ); if ($val === false) {     // Handle error. } elseif ($val === Collator::ON) {     // Do something useful. } ?> ``` ### See Also * [[Collator](class.collator) constants](class.collator#intl.collator-constants) * [collator\_get\_attribute()](collator.getattribute) - Get collation attribute value * [collator\_set\_strength()](collator.setstrength) - Set collation strength php ImagickPixelIterator::getPreviousIteratorRow ImagickPixelIterator::getPreviousIteratorRow ============================================ (PECL imagick 2, PECL imagick 3) ImagickPixelIterator::getPreviousIteratorRow — Returns the previous row ### Description ``` public ImagickPixelIterator::getPreviousIteratorRow(): array ``` **Warning**This function is currently not documented; only its argument list is available. Returns the previous row as an array of pixel wands from the pixel iterator. ### Return Values Returns the previous row as an array of ImagickPixelWand objects from the ImagickPixelIterator, throwing ImagickPixelIteratorException on error. php radius_request_authenticator radius\_request\_authenticator ============================== (PECL radius >= 1.1.0) radius\_request\_authenticator — Returns the request authenticator ### Description ``` radius_request_authenticator(resource $radius_handle): string ``` The request authenticator is needed for demangling mangled data like passwords and encryption-keys. ### Parameters `radius_handle` The RADIUS resource. ### Return Values Returns the request authenticator as string, or **`false`** on error. ### See Also * [radius\_demangle()](function.radius-demangle) - Demangles data php odbc_exec odbc\_exec ========== (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_exec — Directly execute an SQL statement ### Description ``` odbc_exec(resource $odbc, string $query): resource|false ``` Sends an SQL statement to the database server. ### Parameters `odbc` The ODBC connection identifier, see [odbc\_connect()](function.odbc-connect) for details. `query` The SQL statement. ### Return Values Returns an ODBC result identifier if the SQL command was executed successfully, or **`false`** on error. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `flags` was removed. | ### See Also * [odbc\_prepare()](function.odbc-prepare) - Prepares a statement for execution * [odbc\_execute()](function.odbc-execute) - Execute a prepared statement php SolrQuery::getExpand SolrQuery::getExpand ==================== (PECL solr >= 2.2.0) SolrQuery::getExpand — Returns true if group expanding is enabled ### Description ``` public SolrQuery::getExpand(): bool ``` Returns **`true`** if group expanding is enabled ### Parameters This function has no parameters. ### Return Values Returns whether group expanding is enabled. php SplPriorityQueue::top SplPriorityQueue::top ===================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) SplPriorityQueue::top — Peeks at the node from the top of the queue ### Description ``` public SplPriorityQueue::top(): mixed ``` ### Parameters This function has no parameters. ### Return Values The value or priority (or both) of the top node, depending on the extract flag. php Imagick::listRegistry Imagick::listRegistry ===================== (PECL imagick 3 >= 3.3.0) Imagick::listRegistry — Description ### Description ``` public static Imagick::listRegistry(): array ``` List all the registry settings. Returns an array of all the key/value pairs in the registry ### Parameters This function has no parameters. ### Return Values An array containing the key/values from the registry. php ftp_chdir ftp\_chdir ========== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_chdir — Changes the current directory on a FTP server ### Description ``` ftp_chdir(FTP\Connection $ftp, string $directory): bool ``` Changes the current directory to the specified one. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `directory` The target directory. ### Return Values Returns **`true`** on success or **`false`** on failure. If changing directory fails, PHP will also throw a warning. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_chdir()** example** ``` <?php // set up basic connection $ftp = ftp_connect($ftp_server);  // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass);  // check connection if ((!$ftp) || (!$login_result)) {     die("FTP connection has failed !"); } echo "Current directory: " . ftp_pwd($ftp) . "\n"; // try to change the directory to somedir if (ftp_chdir($ftp, "somedir")) {     echo "Current directory is now: " . ftp_pwd($ftp) . "\n"; } else {      echo "Couldn't change directory\n"; } // close the connection ftp_close($ftp); ?> ``` ### See Also * [ftp\_cdup()](function.ftp-cdup) - Changes to the parent directory * [ftp\_pwd()](function.ftp-pwd) - Returns the current directory name php Zookeeper::getChildren Zookeeper::getChildren ====================== (PECL zookeeper >= 0.1.0) Zookeeper::getChildren — Lists the children of a node synchronously ### Description ``` public Zookeeper::getChildren(string $path, callable $watcher_cb = null): array ``` ### Parameters `path` The name of the node. Expressed as a file name with slashes separating ancestors of the node. `watcher_cb` If nonzero, a watch will be set at the server to notify the client if the node changes. ### Return Values Returns an array with children paths on success, and false on failure. ### Errors/Exceptions This method emits PHP error/warning when parameters count or types are wrong or fail to list children of a node. **Caution** Since version 0.3.0, this method emits [ZookeeperException](class.zookeeperexception) and it's derivatives. ### Examples **Example #1 **Zookeeper::getChildren()** example** Lists children of a node. ``` <?php $zookeeper = new Zookeeper('locahost:2181'); $path = '/zookeeper'; $r = $zookeeper->getchildren($path); if ($r)   var_dump($r); else   echo 'ERR'; ?> ``` The above example will output: ``` array(1) { [0]=> string(6) "config" } ``` ### See Also * [Zookeeper::create()](zookeeper.create) - Create a node synchronously * [Zookeeper::delete()](zookeeper.delete) - Delete a node in zookeeper synchronously * [ZookeeperException](class.zookeeperexception) php DOMXPath::query DOMXPath::query =============== (PHP 5, PHP 7, PHP 8) DOMXPath::query — Evaluates the given XPath expression ### Description ``` public DOMXPath::query(string $expression, ?DOMNode $contextNode = null, bool $registerNodeNS = true): mixed ``` Executes the given XPath `expression`. ### Parameters `expression` The XPath expression to execute. `contextNode` The optional `contextNode` can be specified for doing relative XPath queries. By default, the queries are relative to the root element. `registerNodeNS` The optional `registerNodeNS` can be specified to disable automatic registration of the context node. ### Return Values Returns a [DOMNodeList](class.domnodelist) containing all nodes matching the given XPath `expression`. Any expression which does not return nodes will return an empty [DOMNodeList](class.domnodelist). If the `expression` is malformed or the `contextNode` is invalid, **DOMXPath::query()** returns **`false`**. ### Examples **Example #1 Getting all the english books** ``` <?php $doc = new DOMDocument; // We don't want to bother with white spaces $doc->preserveWhiteSpace = false; $doc->load('book.xml'); $xpath = new DOMXPath($doc); // We start from the root element $query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]'; $entries = $xpath->query($query); foreach ($entries as $entry) {     echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .          " by {$entry->previousSibling->nodeValue}\n"; } ?> ``` The above example will output: ``` Found The Grapes of Wrath, by John Steinbeck Found The Pearl, by John Steinbeck ``` We can also use the `contextNode` parameter to shorten our expression: ``` <?php $doc = new DOMDocument; $doc->preserveWhiteSpace = false; $doc->load('book.xml'); $xpath = new DOMXPath($doc); $tbody = $doc->getElementsByTagName('tbody')->item(0); // our query is relative to the tbody node $query = 'row/entry[. = "en"]'; $entries = $xpath->query($query, $tbody); foreach ($entries as $entry) {     echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .          " by {$entry->previousSibling->nodeValue}\n"; } ?> ``` ### See Also * [DOMXPath::evaluate()](domxpath.evaluate) - Evaluates the given XPath expression and returns a typed result if possible php pg_send_execute pg\_send\_execute ================= (PHP 5 >= 5.1.0, PHP 7, PHP 8) pg\_send\_execute — Sends a request to execute a prepared statement with given parameters, without waiting for the result(s) ### Description ``` pg_send_execute(PgSql\Connection $connection, string $statement_name, array $params): int|bool ``` Sends a request to execute a prepared statement with given parameters, without waiting for the result(s). This is similar to [pg\_send\_query\_params()](function.pg-send-query-params), but the command to be executed is specified by naming a previously-prepared statement, instead of giving a query string. The function's parameters are handled identically to [pg\_execute()](function.pg-execute). Like [pg\_execute()](function.pg-execute), it will not work on pre-7.4 versions of PostgreSQL. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. `statement_name` The name of the prepared statement to execute. If "" is specified, then the unnamed statement is executed. The name must have been previously prepared using [pg\_prepare()](function.pg-prepare), [pg\_send\_prepare()](function.pg-send-prepare) or a `PREPARE` SQL command. `params` An array of parameter values to substitute for the $1, $2, etc. placeholders in the original prepared query string. The number of elements in the array must match the number of placeholders. ### Return Values Returns **`true`** on success, **`false`** or `0` on failure. Use [pg\_get\_result()](function.pg-get-result) to determine the query result. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Using **pg\_send\_execute()**** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   // Prepare a query for execution   if (!pg_connection_busy($dbconn)) {     pg_send_prepare($dbconn, "my_query", 'SELECT * FROM shops WHERE name = $1');     $res1 = pg_get_result($dbconn);   }   // Execute the prepared query.  Note that it is not necessary to escape   // the string "Joe's Widgets" in any way   if (!pg_connection_busy($dbconn)) {     pg_send_execute($dbconn, "my_query", array("Joe's Widgets"));     $res2 = pg_get_result($dbconn);   }      // Execute the same prepared query, this time with a different parameter   if (!pg_connection_busy($dbconn)) {     pg_send_execute($dbconn, "my_query", array("Clothes Clothes Clothes"));     $res3 = pg_get_result($dbconn);   }    ?> ``` ### See Also * [pg\_prepare()](function.pg-prepare) - Submits a request to create a prepared statement with the given parameters, and waits for completion * [pg\_send\_prepare()](function.pg-send-prepare) - Sends a request to create a prepared statement with the given parameters, without waiting for completion * [pg\_execute()](function.pg-execute) - Sends a request to execute a prepared statement with given parameters, and waits for the result php XMLWriter::outputMemory XMLWriter::outputMemory ======================= xmlwriter\_output\_memory ========================= (PHP 5 >= 5.1.2, PHP 7, PHP 8, PECL xmlwriter >= 0.1.0) XMLWriter::outputMemory -- xmlwriter\_output\_memory — Returns current buffer ### Description Object-oriented style ``` public XMLWriter::outputMemory(bool $flush = true): string ``` Procedural style ``` xmlwriter_output_memory(XMLWriter $writer, bool $flush = true): string ``` Returns the current buffer. ### Parameters `writer` Only for procedural calls. The [XMLWriter](class.xmlwriter) instance that is being modified. This object is returned from a call to [xmlwriter\_open\_uri()](xmlwriter.openuri) or [xmlwriter\_open\_memory()](xmlwriter.openmemory). `flush` Whether to flush the output buffer or not. Default is **`true`**. ### Return Values Returns the current buffer as a string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `writer` expects an [XMLWriter](class.xmlwriter) instance now; previously, a resource was expected. | ### See Also * [XMLWriter::flush()](xmlwriter.flush) - Flush current buffer php sodium_crypto_box_publickey sodium\_crypto\_box\_publickey ============================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_box\_publickey — Extract the public key from a crypto\_box keypair ### Description ``` sodium_crypto_box_publickey(string $key_pair): string ``` Given a keypair, fetch only the public key. ### Parameters `key_pair` A keypair, such as one generated by [sodium\_crypto\_box\_keypair()](function.sodium-crypto-box-keypair) or [sodium\_crypto\_box\_seed\_keypair()](function.sodium-crypto-box-seed-keypair) ### Return Values X25519 public key. php ReflectionClassConstant::isEnumCase ReflectionClassConstant::isEnumCase =================================== (PHP 8 >= 8.1.0) ReflectionClassConstant::isEnumCase — Checks if class constant is an Enum case ### Description ``` public ReflectionClassConstant::isEnumCase(): bool ``` Checks if the class constant is an [Enum](https://www.php.net/manual/en/language.enumerations.php) case. ### Parameters This function has no parameters. ### Return Values **`true`** if the class constant is an Enum case; **`false`** otherwise. ### Examples **Example #1 **ReflectionClassConstant::isEnumCase()** example** Distinguish between Enum cases and regular class constants. ``` <?php enum Status {     const BORING_CONSTANT = 'test';     const ENUM_VALUE = Status::PUBLISHED;     case DRAFT;     case PUBLISHED;     case ARCHIVED; } $reflection = new ReflectionEnum(Status::class); foreach ($reflection->getReflectionConstants() as $constant) {     echo "{$constant->name} is ",         $constant->isEnumCase() ? "an enum case" : "a regular class constant",         PHP_EOL; } ?> ``` The above example will output: ``` BORING_CONSTANT is a regular class constant ENUM_VALUE is a regular class constant DRAFT is an enum case PUBLISHED is an enum case ARCHIVED is an enum case ``` ### See Also * [ReflectionEnum](class.reflectionenum) php SolrQuery::setFacet SolrQuery::setFacet =================== (PECL solr >= 0.9.2) SolrQuery::setFacet — Maps to the facet parameter. Enables or disables facetting ### Description ``` public SolrQuery::setFacet(bool $flag): SolrQuery ``` Enables or disables faceting. ### Parameters `value` **`true`** enables faceting and **`false`** disables it. ### Return Values Returns the current SolrQuery object, if the return value is used. php ReflectionClass::getTraitNames ReflectionClass::getTraitNames ============================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) ReflectionClass::getTraitNames — Returns an array of names of traits used by this class ### Description ``` public ReflectionClass::getTraitNames(): array ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values Returns an array with trait names in values. Returns **`null`** in case of an error. php IntlChar::isIDIgnorable IntlChar::isIDIgnorable ======================= (PHP 7, PHP 8) IntlChar::isIDIgnorable — Check if code point is an ignorable character ### Description ``` public static IntlChar::isIDIgnorable(int|string $codepoint): ?bool ``` Determines if the specified character should be regarded as an ignorable character in an identifier. **`true`** for characters with general category "Cf" (format controls) as well as non-whitespace ISO controls (U+0000..U+0008, U+000E..U+001B, U+007F..U+009F). > > **Note**: > > > Note that Unicode just recommends to ignore Cf (format controls). > > ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) ### Return Values Returns **`true`** if `codepoint` is ignorable in identifiers, **`false`** if not. Returns **`null`** on failure. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::isIDIgnorable("A")); var_dump(IntlChar::isIDIgnorable(" ")); var_dump(IntlChar::isIDIgnorable("\u{007F}")); ?> ``` The above example will output: ``` bool(false) bool(false) bool(true) ``` ### See Also * [IntlChar::isIDStart()](intlchar.isidstart) - Check if code point is permissible as the first character in an identifier * [IntlChar::isIDPart()](intlchar.isidpart) - Check if code point is permissible in an identifier * **`IntlChar::PROPERTY_DEFAULT_IGNORABLE_CODE_POINT`** php EventDnsBase::clearSearch EventDnsBase::clearSearch ========================= (PECL event >= 1.2.6-beta) EventDnsBase::clearSearch — Removes all current search suffixes ### Description ``` public EventDnsBase::clearSearch(): void ``` Removes all current search suffixes from the DNS base; the [EventDnsBase::addSearch()](eventdnsbase.addsearch) function adds a suffix. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [EventDnsBase::addSearch()](eventdnsbase.addsearch) - Adds a domain to the list of search domains php Yaf_View_Interface::setScriptPath Yaf\_View\_Interface::setScriptPath =================================== (Yaf >=1.0.0) Yaf\_View\_Interface::setScriptPath — The setScriptPath purpose ### Description ``` abstract public Yaf_View_Interface::setScriptPath(string $template_dir): void ``` Set the templates base directory, this is usually called by [Yaf\_Dispatcher](class.yaf-dispatcher) **Warning**This function is currently not documented; only its argument list is available. ### Parameters `template_dir` A absolute path to the template directory, by default, [Yaf\_Dispatcher](class.yaf-dispatcher) use [application.directory](https://www.php.net/manual/en/yaf.appconfig.php#configuration.yaf.directory) . "/views" as this paramter. ### Return Values
programming_docs
php The Parle\Parser class The Parle\Parser class ====================== Introduction ------------ (PECL parle >= 0.5.1) Parser class. Rules can be defined on the fly. Once finalized, a [Parle\Lexer](class.parle-lexer) instance is required to deliver the token stream. Class synopsis -------------- class **Parle\Parser** { /\* Constants \*/ const int [ACTION\_ERROR](class.parle-parser#parle-parser.constants.action-error) = 0; const int [ACTION\_SHIFT](class.parle-parser#parle-parser.constants.action-shift) = 1; const int [ACTION\_REDUCE](class.parle-parser#parle-parser.constants.action-reduce) = 2; const int [ACTION\_GOTO](class.parle-parser#parle-parser.constants.action-goto) = 3; const int [ACTION\_ACCEPT](class.parle-parser#parle-parser.constants.action-accept) = 4; const int [ERROR\_SYNTAX](class.parle-parser#parle-parser.constants.error-syntax) = 0; const int [ERROR\_NON\_ASSOCIATIVE](class.parle-parser#parle-parser.constants.error-non-associative) = 1; const int [ERROR\_UNKNOWN\_TOKEN](class.parle-parser#parle-parser.constants.error-unknown-token) = 2; /\* Properties \*/ public int [$action](class.parle-parser#parle-parser.props.action) = 0; public int [$reduceId](class.parle-parser#parle-parser.props.reduceId) = 0; /\* Methods \*/ ``` public advance(): void ``` ``` public build(): void ``` ``` public consume(string $data, Parle\Lexer $lexer): void ``` ``` public dump(): void ``` ``` public errorInfo(): Parle\ErrorInfo ``` ``` public left(string $tok): void ``` ``` public nonassoc(string $tok): void ``` ``` public precedence(string $tok): void ``` ``` public push(string $name, string $rule): int ``` ``` public reset(int $tokenId = ?): void ``` ``` public right(string $tok): void ``` ``` public sigil(int $idx): string ``` ``` public token(string $tok): void ``` ``` public tokenId(string $tok): int ``` ``` public trace(): string ``` ``` public validate(string $data, Parle\Lexer $lexer): bool ``` } Predefined Constants -------------------- **`Parle\Parser::ACTION_ERROR`** **`Parle\Parser::ACTION_SHIFT`** **`Parle\Parser::ACTION_REDUCE`** **`Parle\Parser::ACTION_GOTO`** **`Parle\Parser::ACTION_ACCEPT`** **`Parle\Parser::ERROR_SYNTAX`** **`Parle\Parser::ERROR_NON_ASSOCIATIVE`** **`Parle\Parser::ERROR_UNKNOWN_TOKEN`** Properties ---------- action Current parser action that matches one of the action class constants, readonly. reduceId Grammar rule id just processed in the reduce action. The value corresponds either to a token or to a production id. Readonly. Table of Contents ----------------- * [Parle\Parser::advance](parle-parser.advance) — Process next parser rule * [Parle\Parser::build](parle-parser.build) — Finalize the grammar rules * [Parle\Parser::consume](parle-parser.consume) — Consume the data for processing * [Parle\Parser::dump](parle-parser.dump) — Dump the grammar * [Parle\Parser::errorInfo](parle-parser.errorinfo) — Retrieve the error information * [Parle\Parser::left](parle-parser.left) — Declare a token with left-associativity * [Parle\Parser::nonassoc](parle-parser.nonassoc) — Declare a token with no associativity * [Parle\Parser::precedence](parle-parser.precedence) — Declare a precedence rule * [Parle\Parser::push](parle-parser.push) — Add a grammar rule * [Parle\Parser::reset](parle-parser.reset) — Reset parser state * [Parle\Parser::right](parle-parser.right) — Declare a token with right-associativity * [Parle\Parser::sigil](parle-parser.sigil) — Retrieve a matching part of a rule * [Parle\Parser::token](parle-parser.token) — Declare a token * [Parle\Parser::tokenId](parle-parser.tokenid) — Get token id * [Parle\Parser::trace](parle-parser.trace) — Trace the parser operation * [Parle\Parser::validate](parle-parser.validate) — Validate input php imap_fetchtext imap\_fetchtext =============== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_fetchtext — Alias of [imap\_body()](function.imap-body) ### Description This function is an alias of: [imap\_body()](function.imap-body). php The SysvSharedMemory class The SysvSharedMemory class ========================== Introduction ------------ (PHP 8) A fully opaque class which replaces a `sysvshm` resource as of PHP 8.0.0. Class synopsis -------------- final class **SysvSharedMemory** { } php log log === (PHP 4, PHP 5, PHP 7, PHP 8) log — Natural logarithm ### Description ``` log(float $num, float $base = M_E): float ``` If the optional `base` parameter is specified, **log()** returns logbase `num`, otherwise **log()** returns the natural logarithm of `num`. ### Parameters `num` The value to calculate the logarithm for `base` The optional logarithmic base to use (defaults to 'e' and so to the natural logarithm). ### Return Values The logarithm of `num` to `base`, if given, or the natural logarithm. ### See Also * [log10()](function.log10) - Base-10 logarithm * [exp()](function.exp) - Calculates the exponent of e * [pow()](function.pow) - Exponential expression php hash_hmac_algos hash\_hmac\_algos ================= (PHP 7 >= 7.2.0, PHP 8) hash\_hmac\_algos — Return a list of registered hashing algorithms suitable for hash\_hmac ### Description ``` hash_hmac_algos(): array ``` ### Parameters This function has no parameters. ### Return Values Returns a numerically indexed array containing the list of supported hashing algorithms suitable for [hash\_hmac()](function.hash-hmac). ### Examples **Example #1 **hash\_hmac\_algos()** example** ``` <?php print_r(hash_hmac_algos()); ``` The above example will output something similar to: ``` Array ( [0] => md2 [1] => md4 [2] => md5 [3] => sha1 [4] => sha224 [5] => sha256 [6] => sha384 [7] => sha512/224 [8] => sha512/256 [9] => sha512 [10] => sha3-224 [11] => sha3-256 [12] => sha3-384 [13] => sha3-512 [14] => ripemd128 [15] => ripemd160 [16] => ripemd256 [17] => ripemd320 [18] => whirlpool [19] => tiger128,3 [20] => tiger160,3 [21] => tiger192,3 [22] => tiger128,4 [23] => tiger160,4 [24] => tiger192,4 [25] => snefru [26] => snefru256 [27] => gost [28] => gost-crypto [29] => haval128,3 [30] => haval160,3 [31] => haval192,3 [32] => haval224,3 [33] => haval256,3 [34] => haval128,4 [35] => haval160,4 [36] => haval192,4 [37] => haval224,4 [38] => haval256,4 [39] => haval128,5 [40] => haval160,5 [41] => haval192,5 [42] => haval224,5 [43] => haval256,5 ) ``` ### Notes > > **Note**: > > > Before PHP 7.2.0 the only means to get a list of supported hash algorithms has been to call [hash\_algos()](function.hash-algos) which also returns hash algorithms that are not suitable for [hash\_hmac()](function.hash-hmac). > > ### See Also * [hash\_hmac()](function.hash-hmac) - Generate a keyed hash value using the HMAC method * [hash\_algos()](function.hash-algos) - Return a list of registered hashing algorithms php ReflectionFunctionAbstract::getStartLine ReflectionFunctionAbstract::getStartLine ======================================== (PHP 5 >= 5.2.0, PHP 7, PHP 8) ReflectionFunctionAbstract::getStartLine — Gets starting line number ### Description ``` public ReflectionFunctionAbstract::getStartLine(): int|false ``` Gets the starting line number of the function. ### Parameters This function has no parameters. ### Return Values The starting line number, or **`false`** if unknown. ### See Also * [ReflectionFunctionAbstract::getEndLine()](reflectionfunctionabstract.getendline) - Gets end line number php xdiff_file_patch_binary xdiff\_file\_patch\_binary ========================== (PECL xdiff >= 0.2.0) xdiff\_file\_patch\_binary — Alias of [xdiff\_file\_bpatch()](function.xdiff-file-bpatch) ### Description ``` xdiff_file_patch_binary(string $file, string $patch, string $dest): bool ``` Patches a `file` with a binary `patch` and stores the result in a file `dest`. This function accepts patches created both via [xdiff\_file\_bdiff()](function.xdiff-file-bdiff) or [xdiff\_file\_rabdiff()](function.xdiff-file-rabdiff) functions or their string counterparts. Starting with version 1.5.0 this function is an alias of [xdiff\_file\_bpatch()](function.xdiff-file-bpatch). ### Parameters `file` The original file. `patch` The binary patch file. `dest` Path of the resulting file. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 **xdiff\_file\_patch\_binary()** example** The following code applies binary diff to a file. ``` <?php $old_version = 'archive-1.0.tgz'; $patch = 'archive.bpatch'; $result = xdiff_file_patch_binary($old_version, $patch, 'archive-1.1.tgz'); if ($result) {    echo "File patched"; } else {    echo "File couldn't be patched"; } ?> ``` ### Notes > > **Note**: > > > Both files (`file` and `patch`) will be loaded into memory so ensure that your memory\_limit is set high enough. > > ### See Also * [xdiff\_string\_patch\_binary()](function.xdiff-string-patch-binary) - Alias of xdiff\_string\_bpatch php sodium_crypto_sign_ed25519_sk_to_curve25519 sodium\_crypto\_sign\_ed25519\_sk\_to\_curve25519 ================================================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_sign\_ed25519\_sk\_to\_curve25519 — Convert an Ed25519 secret key to a Curve25519 secret key ### Description ``` sodium_crypto_sign_ed25519_sk_to_curve25519(string $secret_key): string ``` Given an Ed25519 secret key, calculate the birationally equivalent X25519 secret key. ### Parameters `secret_key` Secret key suitable for the crypto\_sign functions. ### Return Values Secret key suitable for the crypto\_box functions. php stats_cdf_weibull stats\_cdf\_weibull =================== (PECL stats >= 1.0.0) stats\_cdf\_weibull — Calculates any one parameter of the Weibull distribution given values for the others ### Description ``` stats_cdf_weibull( float $par1, float $par2, float $par3, int $which ): float ``` Returns the cumulative distribution function, its inverse, or one of its parameters, of the Weibull distribution. The kind of the return value and parameters (`par1`, `par2`, and `par3`) are determined by `which`. The following table lists the return value and parameters by `which`. CDF, x, k, and lambda denotes cumulative distribution function, the value of the random variable, the shape and the scale parameter of the Weibull distribution, respectively. **Return value and parameters**| `which` | Return value | `par1` | `par2` | `par3` | | --- | --- | --- | --- | --- | | 1 | CDF | x | k | lambda | | 2 | x | CDF | k | lambda | | 3 | k | x | CDF | lambda | | 4 | lambda | x | CDF | k | ### Parameters `par1` The first parameter `par2` The second parameter `par3` The third parameter `which` The flag to determine what to be calculated ### Return Values Returns CDF, x, k, or lambda, determined by `which`. php openal_listener_set openal\_listener\_set ===================== (PECL openal >= 0.1.0) openal\_listener\_set — Set a listener property ### Description ``` openal_listener_set(int $property, mixed $setting): bool ``` ### Parameters `property` Property to set, one of: **`AL_GAIN`** (float), **`AL_POSITION`** (array(float,float,float)), **`AL_VELOCITY`** (array(float,float,float)) and **`AL_ORIENTATION`** (array(float,float,float)). `setting` Value to set, either float, or an array of floats as appropriate. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [openal\_listener\_get()](function.openal-listener-get) - Retrieve a listener property php RarArchive::__toString RarArchive::\_\_toString ======================== (PECL rar >= 2.0.0) RarArchive::\_\_toString — Get text representation ### Description ``` public RarArchive::__toString(): string ``` Provides a string representation for this [RarArchive](class.rararchive) object. It currently shows the full path name of the archive volume that was opened and whether the resource is valid or was already closed through a call to [RarArchive::close()](rararchive.close). This method may be used only for debugging purposes, as there are no guarantees as to which information the result contains or how it is formatted. ### Parameters This function has no parameters. ### Return Values A textual representation of this [RarArchive](class.rararchive) object. The content of this representation is unspecified. ### Examples **Example #1 **RarArchive::\_\_toString()** example** ``` <?php $rar_arch = RarArchive::open('latest_winrar.rar'); echo $rar_arch."\n"; $rar_arch->close(); echo $rar_arch."\n"; ?> ``` The above example will output something similar to: ``` RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" RAR Archive "D:\php_rar\trunk\tests\latest_winrar.rar" (closed) ``` php ldap_set_option ldap\_set\_option ================= (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ldap\_set\_option — Set the value of the given option ### Description ``` ldap_set_option(?LDAP\Connection $ldap, int $option, array|string|int|bool $value): bool ``` Sets the value of the specified option to be `value`. ### Parameters `ldap` Either an [LDAP\Connection](class.ldap-connection) instance, returned by [ldap\_connect()](function.ldap-connect), to set the option for that connection, or **`null`** to set the option globally. `option` The parameter `option` can be one of: | Option | Type | Available since | | --- | --- | --- | | **`LDAP_OPT_DEREF`** | int | | | **`LDAP_OPT_SIZELIMIT`** | int | | | **`LDAP_OPT_TIMELIMIT`** | int | | | **`LDAP_OPT_NETWORK_TIMEOUT`** | int | | | **`LDAP_OPT_PROTOCOL_VERSION`** | int | | | **`LDAP_OPT_ERROR_NUMBER`** | int | | | **`LDAP_OPT_REFERRALS`** | bool | | | **`LDAP_OPT_RESTART`** | bool | | | **`LDAP_OPT_HOST_NAME`** | string | | | **`LDAP_OPT_ERROR_STRING`** | string | | | **`LDAP_OPT_DIAGNOSTIC_MESSAGE`** | string | | | **`LDAP_OPT_MATCHED_DN`** | string | | | **`LDAP_OPT_SERVER_CONTROLS`** | array | | | **`LDAP_OPT_CLIENT_CONTROLS`** | array | | | **`LDAP_OPT_X_KEEPALIVE_IDLE`** | int | PHP 7.1.0 | | **`LDAP_OPT_X_KEEPALIVE_PROBES`** | int | PHP 7.1.0 | | **`LDAP_OPT_X_KEEPALIVE_INTERVAL`** | int | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CACERTDIR`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CACERTFILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CERTFILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CIPHER_SUITE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CRLCHECK`** | int | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_CRLFILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_DHFILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_KEYFILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_PROTOCOL_MIN`** | int | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_RANDOM_FILE`** | string | PHP 7.1.0 | | **`LDAP_OPT_X_TLS_REQUIRE_CERT`** | int | PHP 7.0.5 | **`LDAP_OPT_SERVER_CONTROLS`** and **`LDAP_OPT_CLIENT_CONTROLS`** require a list of controls, this means that the value must be an array of controls. A control consists of an *oid* identifying the control, an optional *value*, and an optional flag for *criticality*. In PHP a control is given by an array containing an element with the key *oid* and string value, and two optional elements. The optional elements are key *value* with string value and key *iscritical* with boolean value. *iscritical* defaults to ***`false`*** if not supplied. See [» draft-ietf-ldapext-ldap-c-api-xx.txt](http://www.openldap.org/devel/cvsweb.cgi/~checkout~/doc/drafts/draft-ietf-ldapext-ldap-c-api-xx.txt) for details. See also the second example below. `value` The new value for the specified `option`. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ldap` parameter expects an [LDAP\Connection](class.ldap-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 Set protocol version** ``` <?php // $ds is a valid LDAP\Connection instance for a directory server if (ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3)) {     echo "Using LDAPv3"; } else {     echo "Failed to set protocol version to 3"; } ?> ``` **Example #2 Set server controls** ``` <?php // $ds is a valid LDAP\Connection instance for a directory server // control with no value $ctrl1 = array("oid" => "1.2.752.58.10.1", "iscritical" => true); // iscritical defaults to FALSE $ctrl2 = array("oid" => "1.2.752.58.1.10", "value" => "magic"); // try to set both controls if (!ldap_set_option($ds, LDAP_OPT_SERVER_CONTROLS, array($ctrl1, $ctrl2))) {     echo "Failed to set server controls"; } ?> ``` ### Notes > > **Note**: > > > This function is only available when using OpenLDAP 2.x.x OR Netscape Directory SDK x.x. > > ### See Also * [ldap\_get\_option()](function.ldap-get-option) - Get the current value for given option php Yaf_Plugin_Abstract::preDispatch Yaf\_Plugin\_Abstract::preDispatch ================================== (Yaf >=1.0.0) Yaf\_Plugin\_Abstract::preDispatch — The preDispatch purpose ### Description ``` public Yaf_Plugin_Abstract::preDispatch(Yaf_Request_Abstract $request, Yaf_Response_Abstract $response): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `request` `response` ### Return Values php $_SERVER $\_SERVER ========= (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) $\_SERVER — Server and execution environment information ### Description $\_SERVER is an array containing information such as headers, paths, and script locations. The entries in this array are created by the web server, therefore there is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here. However, most of these variables are accounted for in the [» CGI/1.1 specification](http://www.faqs.org/rfcs/rfc3875), and are likely to be defined. > **Note**: When running PHP on the [command line](https://www.php.net/manual/en/features.commandline.php) most of these entries will not be available or have any meaning. > > In addition to the elements listed below, PHP will create additional elements with values from request headers. These entries will be named `HTTP_` followed by the header name, capitalized and with underscores instead of hyphens. For example, the `Accept-Language` header would be available as `$_SERVER['HTTP_ACCEPT_LANGUAGE']`. ### Indices 'PHP\_SELF' The filename of the currently executing script, relative to the document root. For instance, $\_SERVER['PHP\_SELF'] in a script at the address http://example.com/foo/bar.php would be /foo/bar.php. The [\_\_FILE\_\_](language.constants.predefined) constant contains the full path and filename of the current (i.e. included) file. If PHP is running as a command-line processor this variable contains the script name. '[argv](reserved.variables.argv)' Array of arguments passed to the script. When the script is run on the command line, this gives C-style access to the command line parameters. When called via the GET method, this will contain the query string. '[argc](reserved.variables.argc)' Contains the number of command line parameters passed to the script (if run on the command line). 'GATEWAY\_INTERFACE' What revision of the CGI specification the server is using; e.g. `'CGI/1.1'`. 'SERVER\_ADDR' The IP address of the server under which the current script is executing. 'SERVER\_NAME' The name of the server host under which the current script is executing. If the script is running on a virtual host, this will be the value defined for that virtual host. > **Note**: Under Apache 2, `UseCanonicalName = On` and `ServerName` must be set. Otherwise, this value reflects the hostname supplied by the client, which can be spoofed. It is not safe to rely on this value in security-dependent contexts. > > 'SERVER\_SOFTWARE' Server identification string, given in the headers when responding to requests. 'SERVER\_PROTOCOL' Name and revision of the information protocol via which the page was requested; e.g. `'HTTP/1.0'`; 'REQUEST\_METHOD' Which request method was used to access the page; e.g. `'GET'`, `'HEAD'`, `'POST'`, `'PUT'`. > > **Note**: > > > PHP script is terminated after sending headers (it means after producing any output without output buffering) if the request method was `HEAD`. > > 'REQUEST\_TIME' The timestamp of the start of the request. 'REQUEST\_TIME\_FLOAT' The timestamp of the start of the request, with microsecond precision. 'QUERY\_STRING' The query string, if any, via which the page was accessed. 'DOCUMENT\_ROOT' The document root directory under which the current script is executing, as defined in the server's configuration file. 'HTTPS' Set to a non-empty value if the script was queried through the HTTPS protocol. 'REMOTE\_ADDR' The IP address from which the user is viewing the current page. 'REMOTE\_HOST' The Host name from which the user is viewing the current page. The reverse dns lookup is based on the REMOTE\_ADDR of the user. > **Note**: The web server must be configured to create this variable. For example in Apache `HostnameLookups On` must be set inside httpd.conf for it to exist. See also [gethostbyaddr()](function.gethostbyaddr). > > 'REMOTE\_PORT' The port being used on the user's machine to communicate with the web server. 'REMOTE\_USER' The authenticated user. 'REDIRECT\_REMOTE\_USER' The authenticated user if the request is internally redirected. 'SCRIPT\_FILENAME' The absolute pathname of the currently executing script. > > **Note**: > > > If a script is executed with the CLI, as a relative path, such as file.php or ../file.php, $\_SERVER['SCRIPT\_FILENAME'] will contain the relative path specified by the user. > > 'SERVER\_ADMIN' The value given to the SERVER\_ADMIN (for Apache) directive in the web server configuration file. If the script is running on a virtual host, this will be the value defined for that virtual host. 'SERVER\_PORT' The port on the server machine being used by the web server for communication. For default setups, this will be `'80'`; using SSL, for instance, will change this to whatever your defined secure HTTP port is. > **Note**: Under Apache 2, `UseCanonicalName = On`, as well as `UseCanonicalPhysicalPort = On` must be set in order to get the physical (real) port, otherwise, this value can be spoofed, and it may or may not return the physical port value. It is not safe to rely on this value in security-dependent contexts. > > 'SERVER\_SIGNATURE' String containing the server version and virtual host name which are added to server-generated pages, if enabled. 'PATH\_TRANSLATED' Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. > **Note**: Apache 2 users may use `AcceptPathInfo = On` inside httpd.conf to define PATH\_INFO. > > 'SCRIPT\_NAME' Contains the current script's path. This is useful for pages which need to point to themselves. The [\_\_FILE\_\_](language.constants.predefined) constant contains the full path and filename of the current (i.e. included) file. 'REQUEST\_URI' The URI which was given in order to access this page; for instance, '`/index.html`'. 'PHP\_AUTH\_DIGEST' When doing Digest HTTP authentication this variable is set to the 'Authorization' header sent by the client (which you should then use to make the appropriate validation). 'PHP\_AUTH\_USER' When doing HTTP authentication this variable is set to the username provided by the user. 'PHP\_AUTH\_PW' When doing HTTP authentication this variable is set to the password provided by the user. 'AUTH\_TYPE' When doing HTTP authentication this variable is set to the authentication type. 'PATH\_INFO' Contains any client-provided pathname information trailing the actual script filename but preceding the query string, if available. For instance, if the current script was accessed via the URI http://www.example.com/php/path\_info.php/some/stuff?foo=bar, then $\_SERVER['PATH\_INFO'] would contain `/some/stuff`. 'ORIG\_PATH\_INFO' Original version of 'PATH\_INFO' before processed by PHP. ### Examples **Example #1 $\_SERVER example** ``` <?php echo $_SERVER['SERVER_NAME']; ?> ``` The above example will output something similar to: ``` www.example.com ``` ### Notes > > **Note**: > > > This is a 'superglobal', or automatic global, variable. This simply means that it is available in all scopes throughout a script. There is no need to do **global $variable;** to access it within functions or methods. > > > ### See Also * [The filter extension](https://www.php.net/manual/en/book.filter.php)
programming_docs
php Ds\Stack::copy Ds\Stack::copy ============== (PECL ds >= 1.0.0) Ds\Stack::copy — Returns a shallow copy of the stack ### Description ``` public Ds\Stack::copy(): Ds\Stack ``` Returns a shallow copy of the stack. ### Parameters This function has no parameters. ### Return Values Returns a shallow copy of the stack. ### Examples **Example #1 **Ds\Stack::copy()** example** ``` <?php $a = new \Ds\Stack([1, 2, 3]); $b = $a->copy(); // Updating the copy doesn't affect the original $b->push(4); print_r($a); print_r($b); ?> ``` The above example will output something similar to: ``` Ds\Stack Object ( [0] => 3 [1] => 2 [2] => 1 ) Ds\Stack Object ( [0] => 4 [1] => 3 [2] => 2 [3] => 1 ) ``` php IntlChar::charName IntlChar::charName ================== (PHP 7, PHP 8) IntlChar::charName — Retrieve the name of a Unicode character ### Description ``` public static IntlChar::charName(int|string $codepoint, int $type = IntlChar::UNICODE_CHAR_NAME): ?string ``` Retrieves the name of a Unicode character. Depending on `type`, the resulting character name is the "modern" name or the name that was defined in Unicode version 1.0. The name contains only "invariant" characters like A-Z, 0-9, space, and '-'. Unicode 1.0 names are only retrieved if they are different from the modern names and if ICU contains the data for them. ### Parameters `codepoint` The int codepoint value (e.g. `0x2603` for *U+2603 SNOWMAN*), or the character encoded as a UTF-8 string (e.g. `"\u{2603}"`) `type` Which set of names to use for the lookup. Can be any of these constants: * **`IntlChar::UNICODE_CHAR_NAME`** (default) * **`IntlChar::UNICODE_10_CHAR_NAME`** * **`IntlChar::EXTENDED_CHAR_NAME`** * **`IntlChar::CHAR_NAME_ALIAS`** * **`IntlChar::CHAR_NAME_CHOICE_COUNT`** ### Return Values The corresponding name, or an empty string if there is no name for this character, or **`null`** if there is no such code point. ### Examples **Example #1 Testing different code points** ``` <?php var_dump(IntlChar::charName(".")); var_dump(IntlChar::charName(".", IntlChar::UNICODE_CHAR_NAME)); var_dump(IntlChar::charName("\u{2603}")); var_dump(IntlChar::charName("\u{0000}")); ?> ``` The above example will output: ``` string(9) "FULL STOP" string(9) "FULL STOP" string(7) "SNOWMAN" string(0) "" ``` ### See Also * [IntlChar::charFromName()](intlchar.charfromname) - Find Unicode character by name and return its code point value * [IntlChar::enumCharNames()](intlchar.enumcharnames) - Enumerate all assigned Unicode characters within a range php Yaf_Request_Abstract::setParam Yaf\_Request\_Abstract::setParam ================================ (Yaf >=1.0.0) Yaf\_Request\_Abstract::setParam — Set a calling parameter to a request ### Description ``` public Yaf_Request_Abstract::setParam(string $name, string $value = ?): bool ``` Set a parameter to request, which can be retrieved by [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) ### Parameters `name` `value` ### Return Values ### See Also * [Yaf\_Request\_Abstract::getParam()](yaf-request-abstract.getparam) - Retrieve calling parameter * [Yaf\_Request\_Abstract::getParams()](yaf-request-abstract.getparams) - Retrieve all calling parameters php Yaf_Config_Simple::__get Yaf\_Config\_Simple::\_\_get ============================ (Yaf >=1.0.0) Yaf\_Config\_Simple::\_\_get — The \_\_get purpose ### Description ``` public Yaf_Config_Simple::__get(string $name = ?): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `name` ### Return Values php Yaf_Dispatcher::dispatch Yaf\_Dispatcher::dispatch ========================= (Yaf >=1.0.0) Yaf\_Dispatcher::dispatch — Dispatch a request ### Description ``` public Yaf_Dispatcher::dispatch(Yaf_Request_Abstract $request): Yaf_Response_Abstract ``` This method does the heavy work of the [Yaf\_Dispatcher](class.yaf-dispatcher). It take a request object. The dispatch process has three distinct events: * Routing * Dispatching * Response Routing takes place exactly once, using the values in the request object when **Yaf\_Dispatcher::dispatch()** is called. Dispatching takes place in a loop; a request may either indicate multiple actions to dispatch, or the controller or a plugin may reset the request object to force additional actions to dispatch(see [Yaf\_Plugin\_Abstract](class.yaf-plugin-abstract). When all is done, the [Yaf\_Dispatcher](class.yaf-dispatcher) returns a response. ### Parameters `request` ### Return Values php Imagick::quantizeImage Imagick::quantizeImage ====================== (PECL imagick 2, PECL imagick 3) Imagick::quantizeImage — Analyzes the colors within a reference image ### Description ``` public Imagick::quantizeImage( int $numberColors, int $colorspace, int $treedepth, bool $dither, bool $measureError ): bool ``` ### Parameters `numberColors` `colorspace` `treedepth` `dither` `measureError` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 **Imagick::quantizeImage()**** ``` <?php function quantizeImage($imagePath, $numberColors, $colorSpace, $treeDepth, $dither) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->quantizeImage($numberColors, $colorSpace, $treeDepth, $dither, false);     $imagick->setImageFormat('png');     header("Content-Type: image/png");     echo $imagick->getImageBlob(); } ?> ``` php GearmanWorker::addServers GearmanWorker::addServers ========================= (PECL gearman >= 0.5.0) GearmanWorker::addServers — Add job servers ### Description ``` public GearmanWorker::addServers(string $servers = 127.0.0.1:4730): bool ``` Adds one or more job servers to this worker. These go into a list of servers that can be used to run jobs. No socket I/O happens here. ### Parameters `servers` A comma separated list of job servers in the format host:port. If no port is specified, it defaults to 4730. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Add two job servers** ``` <?php $worker= new GearmanWorker();  $worker->addServers("10.0.0.1,10.0.0.2:7003"); ?> ``` ### See Also * [GearmanWorker::addServer()](gearmanworker.addserver) - Add a job server php pg_escape_bytea pg\_escape\_bytea ================= (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_escape\_bytea — Escape a string for insertion into a bytea field ### Description ``` pg_escape_bytea(PgSql\Connection $connection = ?, string $data): string ``` **pg\_escape\_bytea()** escapes string for bytea datatype. It returns escaped string. > > **Note**: > > > When you `SELECT` a bytea type, PostgreSQL returns octal byte values prefixed with '\' (e.g. \032). Users are supposed to convert back to binary format manually. > > This function requires PostgreSQL 7.2 or later. With PostgreSQL 7.2.0 and 7.2.1, bytea values must be cast when you enable multi-byte support. i.e. `INSERT INTO test_table (image) > VALUES ('$image_escaped'::bytea);` PostgreSQL 7.2.2 or later does not need a cast. The exception is when the client and backend character encoding does not match, and there may be multi-byte stream error. User must then cast to bytea to avoid this error. > > ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. When `connection` is unspecified, the default connection is used. The default connection is the last connection made by [pg\_connect()](function.pg-connect) or [pg\_pconnect()](function.pg-pconnect). **Warning**As of PHP 8.1.0, using the default connection is deprecated. `data` A string containing text or binary data to be inserted into a bytea column. ### Return Values A string containing the escaped data. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_escape\_bytea()** example** ``` <?php    // Connect to the database   $dbconn = pg_connect('dbname=foo');      // Read in a binary file   $data = file_get_contents('image1.jpg');      // Escape the binary data   $escaped = pg_escape_bytea($data);      // Insert it into the database   pg_query("INSERT INTO gallery (name, data) VALUES ('Pine trees', '{$escaped}')"); ?> ``` ### See Also * [pg\_unescape\_bytea()](function.pg-unescape-bytea) - Unescape binary for bytea type * [pg\_escape\_string()](function.pg-escape-string) - Escape a string for query php sodium_crypto_kdf_keygen sodium\_crypto\_kdf\_keygen =========================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_kdf\_keygen — Generate a random root key for the KDF interface ### Description ``` sodium_crypto_kdf_keygen(): string ``` Generates a random key suitable for serving as the root key for [sodium\_crypto\_kdf\_derive\_from\_key()](function.sodium-crypto-kdf-derive-from-key). ### Parameters This function has no parameters. ### Return Values A random 256-bit key. php xdiff_string_bpatch xdiff\_string\_bpatch ===================== (PECL xdiff >= 1.5.0) xdiff\_string\_bpatch — Patch a string with a binary diff ### Description ``` xdiff_string_bpatch(string $str, string $patch): string ``` Patches a string `str` with a binary `patch`. This function accepts patches created both via [xdiff\_string\_bdiff()](function.xdiff-string-bdiff) and [xdiff\_string\_rabdiff()](function.xdiff-string-rabdiff) functions or their file counterparts. ### Parameters `str` The original binary string. `patch` The binary patch string. ### Return Values Returns the patched string, or **`false`** on error. ### See Also * [xdiff\_string\_bdiff()](function.xdiff-string-bdiff) - Make binary diff of two strings * [xdiff\_string\_rabdiff()](function.xdiff-string-rabdiff) - Make binary diff of two strings using the Rabin's polynomial fingerprinting algorithm php DirectoryIterator::current DirectoryIterator::current ========================== (PHP 5, PHP 7, PHP 8) DirectoryIterator::current — Return the current DirectoryIterator item ### Description ``` public DirectoryIterator::current(): mixed ``` Get the current [DirectoryIterator](class.directoryiterator) item. ### Parameters This function has no parameters. ### Return Values The current [DirectoryIterator](class.directoryiterator) item. ### Examples **Example #1 A **DirectoryIterator::current()** example** This example will list the contents of the directory containing the script. ``` <?php $iterator = new DirectoryIterator(__DIR__); while($iterator->valid()) {     $file = $iterator->current();     echo $iterator->key() . " => " . $file->getFilename() . "\n";     $iterator->next(); } ?> ``` The above example will output something similar to: ``` 0 => . 1 => .. 2 => apple.jpg 3 => banana.jpg 4 => index.php 5 => pear.jpg ``` ### See Also * [DirectoryIterator::key()](directoryiterator.key) - Return the key for the current DirectoryIterator item * [DirectoryIterator::next()](directoryiterator.next) - Move forward to next DirectoryIterator item * [DirectoryIterator::rewind()](directoryiterator.rewind) - Rewind the DirectoryIterator back to the start * [DirectoryIterator::valid()](directoryiterator.valid) - Check whether current DirectoryIterator position is a valid file * [Iterator::current()](iterator.current) - Return the current element php SimpleXMLElement::registerXPathNamespace SimpleXMLElement::registerXPathNamespace ======================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SimpleXMLElement::registerXPathNamespace — Creates a prefix/ns context for the next XPath query ### Description ``` public SimpleXMLElement::registerXPathNamespace(string $prefix, string $namespace): bool ``` Creates a prefix/ns context for the next XPath query. In particular, this is helpful if the provider of the given XML document alters the namespace prefixes. `registerXPathNamespace` will create a prefix for the associated namespace, allowing one to access nodes in that namespace without the need to change code to allow for the new prefixes dictated by the provider. ### Parameters `prefix` The namespace prefix to use in the XPath query for the namespace given in `namespace`. `namespace` The namespace to use for the XPath query. This must match a namespace in use by the XML document or the XPath query using `prefix` will not return any results. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Setting a namespace prefix to use in an XPath query** ``` <?php $xml = <<<EOD <book xmlns:chap="http://example.org/chapter-title">     <title>My Book</title>     <chapter id="1">         <chap:title>Chapter 1</chap:title>         <para>Donec velit. Nullam eget tellus vitae tortor gravida scelerisque.              In orci lorem, cursus imperdiet, ultricies non, hendrerit et, orci.              Nulla facilisi. Nullam velit nisl, laoreet id, condimentum ut,              ultricies id, mauris.</para>     </chapter>     <chapter id="2">         <chap:title>Chapter 2</chap:title>         <para>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Proin              gravida. Phasellus tincidunt massa vel urna. Proin adipiscing quam              vitae odio. Sed dictum. Ut tincidunt lorem ac lorem. Duis eros              tellus, pharetra id, faucibus eu, dapibus dictum, odio.</para>     </chapter> </book> EOD; $sxe = new SimpleXMLElement($xml); $sxe->registerXPathNamespace('c', 'http://example.org/chapter-title'); $result = $sxe->xpath('//c:title'); foreach ($result as $title) {   echo $title . "\n"; } ?> ``` The above example will output: ``` Chapter 1 Chapter 2 ``` Notice how the XML document shown in the example sets a namespace with a prefix of `chap`. Imagine that this document (or another one like it) may have used a prefix of `c` in the past for the same namespace. Since it has changed, the XPath query will no longer return the proper results and the query will require modification. Using `registerXPathNamespace` avoids future modification of the query even if the provider changes the namespace prefix. ### See Also * [SimpleXMLElement::xpath()](simplexmlelement.xpath) - Runs XPath query on XML data * [SimpleXMLElement::getDocNamespaces()](simplexmlelement.getdocnamespaces) - Returns namespaces declared in document * [SimpleXMLElement::getNamespaces()](simplexmlelement.getnamespaces) - Returns namespaces used in document php odbc_close_all odbc\_close\_all ================ (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_close\_all — Close all ODBC connections ### Description ``` odbc_close_all(): void ``` **odbc\_close\_all()** will close down all connections to database server(s). ### Parameters This function has no parameters. ### Return Values No value is returned. ### Notes > > **Note**: > > > This function will fail if there are open transactions on a connection. This connection will remain open in this case. > > php phpdbg_break_next phpdbg\_break\_next =================== (PHP 5 >= 5.6.3, PHP 7, PHP 8) phpdbg\_break\_next — Inserts a breakpoint at the next opcode ### Description ``` phpdbg_break_next(): void ``` Insert a breakpoint at the next opcode. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [phpdbg\_break\_file()](function.phpdbg-break-file) - Inserts a breakpoint at a line in a file * [phpdbg\_break\_function()](function.phpdbg-break-function) - Inserts a breakpoint at entry to a function * [phpdbg\_break\_method()](function.phpdbg-break-method) - Inserts a breakpoint at entry to a method * [phpdbg\_clear()](function.phpdbg-clear) - Clears all breakpoints php finfo_set_flags finfo\_set\_flags ================= finfo::set\_flags ================= (PHP >= 5.3.0, PHP 7, PHP 8, PECL fileinfo >= 0.1.0) finfo\_set\_flags -- finfo::set\_flags — Set libmagic configuration options ### Description Procedural style ``` finfo_set_flags(finfo $finfo, int $flags): bool ``` Object-oriented style ``` public finfo::set_flags(int $flags): bool ``` This function sets various Fileinfo options. Options can be set also directly in [finfo\_open()](function.finfo-open) or other Fileinfo functions. ### Parameters `finfo` An [finfo](class.finfo) instance, returned by [finfo\_open()](function.finfo-open). `flags` One or disjunction of more [Fileinfo constants](https://www.php.net/manual/en/fileinfo.constants.php). ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `finfo` parameter expects an [finfo](class.finfo) instance now; previously, a [resource](language.types.resource) was expected. | php svn_fs_begin_txn2 svn\_fs\_begin\_txn2 ==================== (PECL svn >= 0.2.0) svn\_fs\_begin\_txn2 — Create a new transaction ### Description ``` svn_fs_begin_txn2(resource $repos, int $rev): resource ``` **Warning**This function is currently not documented; only its argument list is available. Create a new transaction ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php ReflectionProperty::isStatic ReflectionProperty::isStatic ============================ (PHP 5, PHP 7, PHP 8) ReflectionProperty::isStatic — Checks if property is static ### Description ``` public ReflectionProperty::isStatic(): bool ``` Checks whether the property is static. ### Parameters This function has no parameters. ### Return Values **`true`** if the property is static, **`false`** otherwise. ### See Also * [ReflectionProperty::isPublic()](reflectionproperty.ispublic) - Checks if property is public * [ReflectionProperty::isProtected()](reflectionproperty.isprotected) - Checks if property is protected * [ReflectionProperty::isPrivate()](reflectionproperty.isprivate) - Checks if property is private * [ReflectionProperty::isReadOnly()](reflectionproperty.isreadonly) - Checks if property is readonly php SessionHandler::close SessionHandler::close ===================== (PHP 5 >= 5.4.0, PHP 7, PHP 8) SessionHandler::close — Close the session ### Description ``` public SessionHandler::close(): bool ``` Closes the current session. This method is automatically executed internally by PHP when closing the session, or explicitly via [session\_write\_close()](function.session-write-close) (which first calls the [SessionHandler::write()](sessionhandler.write)). This method wraps the internal PHP save handler defined in the [session.save\_handler](https://www.php.net/manual/en/session.configuration.php#ini.session.save-handler) ini setting that was set before this handler was activated by [session\_set\_save\_handler()](function.session-set-save-handler). If this class is extended by inheritance, calling the parent `close` method will invoke the wrapper for this method and therefore invoke the associated internal callback. This allows the method to be overridden and or intercepted. For more information on what this method is expected to do, please refer to the documentation at [SessionHandlerInterface::close()](sessionhandlerinterface.close). ### Parameters This function has no parameters. ### Return Values The return value (usually **`true`** on success, **`false`** on failure). Note this value is returned internally to PHP for processing.
programming_docs
php socket_addrinfo_explain socket\_addrinfo\_explain ========================= (PHP 7 >= 7.2.0, PHP 8) socket\_addrinfo\_explain — Get information about addrinfo ### Description ``` socket_addrinfo_explain(AddressInfo $address): array ``` **socket\_addrinfo\_explain()** exposed the underlying `addrinfo` structure. ### Parameters `address` [AddressInfo](class.addressinfo) instance created from [socket\_addrinfo\_lookup()](function.socket-addrinfo-lookup) ### Return Values Returns an array containing the fields in the `addrinfo` structure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `address` is an [AddressInfo](class.addressinfo) instance now; previously, it was a resource. | ### See Also * [socket\_addrinfo\_bind()](function.socket-addrinfo-bind) - Create and bind to a socket from a given addrinfo * [socket\_addrinfo\_connect()](function.socket-addrinfo-connect) - Create and connect to a socket from a given addrinfo * [socket\_addrinfo\_lookup()](function.socket-addrinfo-lookup) - Get array with contents of getaddrinfo about the given hostname php Componere\cast Componere\cast ============== (Componere 2 >= 2.1.2) Componere\cast — Casting ### Description ``` Componere\cast(Type $type, $object): Type ``` ### Parameters `type` A user defined type `object` An object with a user defined type compatible with **Type** ### Return Values An object of type **Type**, cast from `object` ### Errors/Exceptions **Warning** Shall throw [InvalidArgumentException](class.invalidargumentexception) if the type of `object` is or is derived from an internal class **Warning** Shall throw [InvalidArgumentException](class.invalidargumentexception) if **Type** is an interface **Warning** Shall throw [InvalidArgumentException](class.invalidargumentexception) if **Type** is a trait **Warning** Shall throw [InvalidArgumentException](class.invalidargumentexception) if **Type** is an abstract **Warning** Shall throw [InvalidArgumentException](class.invalidargumentexception) if **Type** is not compatible with the type of `object` ### See Also * [Componere\cast\_by\_ref](componere.cast_by_ref) php sodium_crypto_kx_publickey sodium\_crypto\_kx\_publickey ============================= (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_kx\_publickey — Extract the public key from a crypto\_kx keypair ### Description ``` sodium_crypto_kx_publickey(string $key_pair): string ``` Extract the public key from a crypto\_kx keypair. ### Parameters `key_pair` X25519 keypair, such as one generated by [sodium\_crypto\_kx\_keypair()](function.sodium-crypto-kx-keypair). ### Return Values X25519 public key. php ZookeeperConfig::add ZookeeperConfig::add ==================== (PECL zookeeper >= 0.6.0, ZooKeeper >= 3.5.0) ZookeeperConfig::add — Add servers to the ensemble ### Description ``` public ZookeeperConfig::add(string $members, int $version = -1, array &$stat = null): void ``` ### Parameters `members` Comma separated list of servers to be added to the ensemble. Each has a configuration line for a server to be added (as would appear in a configuration file), only for maj. quorums. `version` The expected version of the node. The function will fail if the actual version of the node does not match the expected version. If -1 is used the version check will not take place. `stat` If not NULL, will hold the value of stat for the path on return. ### Return Values No value is returned. ### Errors/Exceptions This method emits [ZookeeperException](class.zookeeperexception) and it's derivatives when parameters count or types are wrong or fail to save value to node. ### Examples **Example #1 **ZookeeperConfig::add()** example** Add members. ``` <?php $client = new Zookeeper(); $client->connect('localhost:2181'); $client->addAuth('digest', 'timandes:timandes'); $zkConfig = $client->getConfig(); $zkConfig->set("server.1=localhost:2888:3888:participant;0.0.0.0:2181"); $zkConfig->add("server.2=localhost:2889:3889:participant;0.0.0.0:2182"); $r = $zkConfig->get(); if ($r)   echo $r; else   echo 'ERR'; ?> ``` The above example will output: ``` server.1=localhost:2888:3888:participant;0.0.0.0:2181 server.2=localhost:2889:3889:participant;0.0.0.0:2182 version=0xca01e881a2 ``` ### See Also * [ZookeeperConfig::get()](zookeeperconfig.get) - Gets the last committed configuration of the ZooKeeper cluster as it is known to the server to which the client is connected, synchronously * [ZookeeperConfig::set()](zookeeperconfig.set) - Change ZK cluster ensemble membership and roles of ensemble peers * [ZookeeperConfig::remove()](zookeeperconfig.remove) - Remove servers from the ensemble * [ZookeeperException](class.zookeeperexception) php version_compare version\_compare ================ (PHP 4 >= 4.1.0, PHP 5, PHP 7, PHP 8) version\_compare — Compares two "PHP-standardized" version number strings ### Description ``` version_compare(string $version1, string $version2, ?string $operator = null): int|bool ``` **version\_compare()** compares two "PHP-standardized" version number strings. The function first replaces `_`, `-` and `+` with a dot `.` in the version strings and also inserts dots `.` before and after any non number so that for example '4.3.2RC1' becomes '4.3.2.RC.1'. Then it compares the parts starting from left to right. If a part contains special version strings these are handled in the following order: `any string not found in this list` < `dev` < `alpha` = `a` < `beta` = `b` < `RC` = `rc` < `#` < `pl` = `p`. This way not only versions with different levels like '4.1' and '4.1.2' can be compared but also any PHP specific version containing development state. ### Parameters `version1` First version number. `version2` Second version number. `operator` An optional operator. The possible operators are: `<`, `lt`, `<=`, `le`, `>`, `gt`, `>=`, `ge`, `==`, `=`, `eq`, `!=`, `<>`, `ne` respectively. This parameter is case-sensitive, values should be lowercase. ### Return Values By default, **version\_compare()** returns `-1` if the first version is lower than the second, `0` if they are equal, and `1` if the second is lower. When using the optional `operator` argument, the function will return **`true`** if the relationship is the one specified by the operator, **`false`** otherwise. ### Examples The examples below use the **`PHP_VERSION`** constant, because it contains the value of the PHP version that is executing the code. **Example #1 **version\_compare()** examples** ``` <?php if (version_compare(PHP_VERSION, '7.0.0') >= 0) {     echo 'I am at least PHP version 7.0.0, my version: ' . PHP_VERSION . "\n"; } if (version_compare(PHP_VERSION, '5.3.0') >= 0) {     echo 'I am at least PHP version 5.3.0, my version: ' . PHP_VERSION . "\n"; } if (version_compare(PHP_VERSION, '5.0.0', '>=')) {     echo 'I am at least PHP version 5.0.0, my version: ' . PHP_VERSION . "\n"; } if (version_compare(PHP_VERSION, '5.0.0', '<')) {     echo 'I am still PHP 4, my version: ' . PHP_VERSION . "\n"; } ?> ``` ### Notes > > **Note**: > > > The **`PHP_VERSION`** constant holds current PHP version. > > > > **Note**: > > > Note that pre-release versions, such as 5.3.0-dev, are considered lower than their final release counterparts (like 5.3.0). > > > > **Note**: > > > Special version strings such as `alpha` and `beta` are case sensitive. Version strings from arbitrary sources that do not adhere to the PHP standard may need to be lowercased via [strtolower()](function.strtolower) before calling **version\_compare()**. > > ### See Also * [phpversion()](function.phpversion) - Gets the current PHP version * [php\_uname()](function.php-uname) - Returns information about the operating system PHP is running on * [function\_exists()](function.function-exists) - Return true if the given function has been defined php Ds\Vector::remove Ds\Vector::remove ================= (PECL ds >= 1.0.0) Ds\Vector::remove — Removes and returns a value by index ### Description ``` public Ds\Vector::remove(int $index): mixed ``` Removes and returns a value by index. ### Parameters `index` The index of the value to remove. ### Return Values The value that was removed. ### Errors/Exceptions [OutOfRangeException](class.outofrangeexception) if the index is not valid. ### Examples **Example #1 **Ds\Vector::remove()** example** ``` <?php $vector = new \Ds\Vector(["a", "b", "c"]); var_dump($vector->remove(1)); var_dump($vector->remove(0)); var_dump($vector->remove(0)); ?> ``` The above example will output something similar to: ``` string(1) "b" string(1) "a" string(1) "c" ``` php putenv putenv ====== (PHP 4, PHP 5, PHP 7, PHP 8) putenv — Sets the value of an environment variable ### Description ``` putenv(string $assignment): bool ``` Adds `assignment` to the server environment. The environment variable will only exist for the duration of the current request. At the end of the request the environment is restored to its original state. ### Parameters `assignment` The setting, like `"FOO=BAR"` ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Setting an environment variable** ``` <?php putenv("UNIQID=$uniqid"); ?> ``` ### See Also * [getenv()](function.getenv) - Gets the value of an environment variable * [apache\_setenv()](function.apache-setenv) - Set an Apache subprocess\_env variable php Phar::getPath Phar::getPath ============= (PHP 5 >= 5.3.0, PHP 7, PHP 8) Phar::getPath — Get the real path to the Phar archive on disk ### Description ``` public Phar::getPath(): string ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php pg_lo_seek pg\_lo\_seek ============ (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_lo\_seek — Seeks position within a large object ### Description ``` pg_lo_seek(PgSql\Lob $lob, int $offset, int $whence = SEEK_CUR): bool ``` **pg\_lo\_seek()** seeks a position within an [PgSql\Lob](class.pgsql-lob) instance. To use the large object interface, it is necessary to enclose it within a transaction block. ### Parameters `lob` An [PgSql\Lob](class.pgsql-lob) instance, returned by [pg\_lo\_open()](function.pg-lo-open). `offset` The number of bytes to seek. `whence` One of the constants **`PGSQL_SEEK_SET`** (seek from object start), **`PGSQL_SEEK_CUR`** (seek from current position) or **`PGSQL_SEEK_END`** (seek from object end) . ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `lob` parameter expects an [PgSql\Lob](class.pgsql-lob) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_lo\_seek()** example** ``` <?php    $doc_oid = 189762345;    $database = pg_connect("dbname=jacarta");    pg_query($database, "begin");    $handle = pg_lo_open($database, $doc_oid, "r");    // Skip first 50000 bytes    pg_lo_seek($handle, 50000, PGSQL_SEEK_SET);    // Read the next 10000 bytes    $data = pg_lo_read($handle, 10000);    pg_query($database, "commit");    echo $data; ?> ``` ### See Also * [pg\_lo\_tell()](function.pg-lo-tell) - Returns current seek position a of large object php GmagickDraw::setfontsize GmagickDraw::setfontsize ======================== (PECL gmagick >= Unknown) GmagickDraw::setfontsize — Sets the font pointsize to use when annotating with text ### Description ``` public GmagickDraw::setfontsize(float $pointsize): GmagickDraw ``` Sets the font pointsize to use when annotating with text. ### Parameters `pointsize` Text pointsize ### Return Values The [GmagickDraw](class.gmagickdraw) object. php strip_tags strip\_tags =========== (PHP 4, PHP 5, PHP 7, PHP 8) strip\_tags — Strip HTML and PHP tags from a string ### Description ``` strip_tags(string $string, array|string|null $allowed_tags = null): string ``` This function tries to return a string with all NULL bytes, HTML and PHP tags stripped from a given `string`. It uses the same tag stripping state machine as the [fgetss()](function.fgetss) function. ### Parameters `string` The input string. `allowed_tags` You can use the optional second parameter to specify tags which should not be stripped. These are either given as string, or as of PHP 7.4.0, as array. Refer to the example below regarding the format of this parameter. > > **Note**: > > > HTML comments and PHP tags are also stripped. This is hardcoded and can not be changed with `allowed_tags`. > > > > **Note**: > > > Self-closing XHTML tags are ignored and only non-self-closing tags should be used in `allowed_tags`. For example, to allow both `<br>` and `<br/>`, you should use: > > > ``` > <?php > strip_tags($input, '<br>'); > ?> > ``` > ### Return Values Returns the stripped string. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `allowed_tags` is nullable now. | | 7.4.0 | The `allowed_tags` now alternatively accepts an array. | ### Examples **Example #1 **strip\_tags()** example** ``` <?php $text = '<p>Test paragraph.</p><!-- Comment --> <a href="#fragment">Other text</a>'; echo strip_tags($text); echo "\n"; // Allow <p> and <a> echo strip_tags($text, '<p><a>'); // as of PHP 7.4.0 the line above can be written as: // echo strip_tags($text, ['p', 'a']); ?> ``` The above example will output: ``` Test paragraph. Other text <p>Test paragraph.</p> <a href="#fragment">Other text</a> ``` ### Notes **Warning** This function should not be used to try to prevent XSS attacks. Use more appropriate functions like [htmlspecialchars()](function.htmlspecialchars) or other means depending on the context of the output. **Warning** Because **strip\_tags()** does not actually validate the HTML, partial or broken tags can result in the removal of more text/data than expected. **Warning** This function does not modify any attributes on the tags that you allow using `allowed_tags`, including the `style` and `onmouseover` attributes that a mischievous user may abuse when posting text that will be shown to other users. > > **Note**: > > > Tag names within the input HTML that are greater than 1023 bytes in length will be treated as though they are invalid, regardless of the `allowed_tags` parameter. > > ### See Also * [htmlspecialchars()](function.htmlspecialchars) - Convert special characters to HTML entities php Imagick::setImageBackgroundColor Imagick::setImageBackgroundColor ================================ (PECL imagick 2, PECL imagick 3) Imagick::setImageBackgroundColor — Sets the image background color ### Description ``` public Imagick::setImageBackgroundColor(mixed $background): bool ``` Sets the image background color. ### Parameters `background` ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the parameter. Previous versions allow only an ImagickPixel object. | php OAuthProvider::reportProblem OAuthProvider::reportProblem ============================ (PECL OAuth >= 1.0.0) OAuthProvider::reportProblem — Report a problem ### Description ``` final public static OAuthProvider::reportProblem(string $oauthexception, bool $send_headers = true): string ``` Pass in a problem as an [OAuthException](class.oauthexception), with possible problems listed in the [OAuth constants](https://www.php.net/manual/en/oauth.constants.php) section. **Warning**This function is currently not documented; only its argument list is available. ### Parameters `oauthexception` The [OAuthException](class.oauthexception). ### Return Values No value is returned. ### See Also * [OAuthProvider::checkOAuthRequest()](oauthprovider.checkoauthrequest) - Check an oauth request * [OAuthProvider::isRequestTokenEndpoint()](oauthprovider.isrequesttokenendpoint) - Sets isRequestTokenEndpoint php svn_fs_is_dir svn\_fs\_is\_dir ================ (PECL svn >= 0.2.0) svn\_fs\_is\_dir — Determines if a path points to a directory ### Description ``` svn_fs_is_dir(resource $root, string $path): bool ``` **Warning**This function is currently not documented; only its argument list is available. Determines if the given path points to a directory. ### Parameters `root` `path` ### Return Values Returns **`true`** if the path points to a directory, **`false`** otherwise. ### Notes **Warning**This function is *EXPERIMENTAL*. The behaviour of this function, its name, and surrounding documentation may change without notice in a future release of PHP. This function should be used at your own risk. php key_exists key\_exists =========== (PHP 4 >= 4.0.6, PHP 5, PHP 7, PHP 8) key\_exists — Alias of [array\_key\_exists()](function.array-key-exists) ### Description This function is an alias of: [array\_key\_exists()](function.array-key-exists). php ZipArchive::locateName ZipArchive::locateName ====================== (PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL zip >= 1.5.0) ZipArchive::locateName — Returns the index of the entry in the archive ### Description ``` public ZipArchive::locateName(string $name, int $flags = 0): int|false ``` Locates an entry using its name. ### Parameters `name` The name of the entry to look up `flags` The flags are specified by ORing the following values, or 0 for none of them. * **`ZipArchive::FL_NOCASE`** * **`ZipArchive::FL_NODIR`** ### Return Values Returns the index of the entry on success or **`false`** on failure. ### Examples **Example #1 Create an archive and then use it with **ZipArchive::locateName()**** ``` <?php $file = 'testlocate.zip'; $zip = new ZipArchive; if ($zip->open($file, ZipArchive::CREATE) !== TRUE) {     exit('failed'); } $zip->addFromString('entry1.txt', 'entry #1'); $zip->addFromString('entry2.txt', 'entry #2'); $zip->addFromString('dir/entry2d.txt', 'entry #2'); if ($zip->status !== ZipArchive::ER_OK) {     echo "failed to write zip\n"; } $zip->close(); if ($zip->open($file) !== TRUE) {     exit('failed'); } echo $zip->locateName('entry1.txt') . "\n"; echo $zip->locateName('eNtry2.txt') . "\n"; echo $zip->locateName('eNtry2.txt', ZipArchive::FL_NOCASE) . "\n"; echo $zip->locateName('enTRy2d.txt', ZipArchive::FL_NOCASE|ZipArchive::FL_NODIR) . "\n"; $zip->close(); ?> ``` The above example will output: ``` 0 1 2 ``` php WeakMap::offsetGet WeakMap::offsetGet ================== (PHP 8) WeakMap::offsetGet — Returns the value pointed to by a certain object ### Description ``` public WeakMap::offsetGet(object $object): mixed ``` Returns the value pointed to by a certain object. ### Parameters `object` Some object contained as key in the map. ### Return Values Returns the value associated to the object passed as argument, **`null`** otherwise. php xml_error_string xml\_error\_string ================== (PHP 4, PHP 5, PHP 7, PHP 8) xml\_error\_string — Get XML parser error string ### Description ``` xml_error_string(int $error_code): ?string ``` Gets the XML parser error string associated with the given `error_code`. ### Parameters `error_code` An error code from [xml\_get\_error\_code()](function.xml-get-error-code). ### Return Values Returns a string with a textual description of the error `error_code`, or **`null`** if no description was found. ### See Also * [xml\_get\_error\_code()](function.xml-get-error-code) - Get XML parser error code
programming_docs
php Yaf_Dispatcher::getDefaultModule Yaf\_Dispatcher::getDefaultModule ================================= (Yaf >=3.2.0) Yaf\_Dispatcher::getDefaultModule — Retrive the default module name ### Description ``` public Yaf_Dispatcher::getDefaultModule(): string ``` get the default module name ### Parameters This function has no parameters. ### Return Values string, module name, default is "Index" php RecursiveIteratorIterator::getMaxDepth RecursiveIteratorIterator::getMaxDepth ====================================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) RecursiveIteratorIterator::getMaxDepth — Get max depth ### Description ``` public RecursiveIteratorIterator::getMaxDepth(): int|false ``` Gets the maximum allowable depth. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The maximum accepted depth, or **`false`** if any depth is allowed. ### See Also * [RecursiveIteratorIterator::setMaxDepth()](recursiveiteratoriterator.setmaxdepth) - Set max depth php mcrypt_module_is_block_algorithm mcrypt\_module\_is\_block\_algorithm ==================================== (PHP 4 >= 4.0.2, PHP 5, PHP 7 < 7.2.0, PECL mcrypt >= 1.0.0) mcrypt\_module\_is\_block\_algorithm — This function checks whether the specified algorithm is a block algorithm **Warning**This function has been *DEPRECATED* as of PHP 7.1.0 and *REMOVED* as of PHP 7.2.0. Relying on this function is highly discouraged. ### Description ``` mcrypt_module_is_block_algorithm(string $algorithm, string $lib_dir = ?): bool ``` This function returns **`true`** if the specified algorithm is a block algorithm, or **`false`** if it is a stream one. ### Parameters `algorithm` The algorithm to check. `lib_dir` The optional `lib_dir` parameter can contain the location where the algorithm module is on the system. ### Return Values This function returns **`true`** if the specified algorithm is a block algorithm, or **`false`** if it is a stream one. php Event::delTimer Event::delTimer =============== (PECL event >= 1.2.6-beta) Event::delTimer — Alias of [Event::del()](event.del) ### Description This method is an alias of: [Event::del()](event.del) php json_last_error_msg json\_last\_error\_msg ====================== (PHP 5 >= 5.5.0, PHP 7, PHP 8) json\_last\_error\_msg — Returns the error string of the last json\_encode() or json\_decode() call ### Description ``` json_last_error_msg(): string ``` Returns the error string of the last [json\_encode()](function.json-encode) or [json\_decode()](function.json-decode) call, which did not specify **`JSON_THROW_ON_ERROR`**. ### Parameters This function has no parameters. ### Return Values Returns the error message on success, or `"No error"` if no error has occurred. ### See Also * [json\_last\_error()](function.json-last-error) - Returns the last error occurred php gnupg_init gnupg\_init =========== (PECL gnupg >= 0.4) gnupg\_init — Initialize a connection ### Description ``` gnupg_init(?array $options = null): resource ``` ### Parameters `options` Must be an associative array. It is used to change the default configuration of the crypto engine. **Configuration overrides**| key | type | description | | --- | --- | --- | | file\_name | string | It is the file name of the executable program implementing this protocol which is usually path of the `gpg` executable. | | home\_dir | string | It is the directory name of the configuration directory. It also overrides `GNUPGHOME` environment variable that is used for the same purpose. | ### Return Values A GnuPG resource connection used by other GnuPG functions. ### Changelog | Version | Description | | --- | --- | | 1.5.0 | The `options` parameter was added. | ### Examples **Example #1 Procedural **gnupg\_init()** example with default setting** ``` <?php $res = gnupg_init(); ?> ``` **Example #2 Procedural **gnupg\_init()** example with overriden file name and home dir** ``` <?php $res = gnupg_init(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]); ?> ``` **Example #3 OO gnupg initializer example with default setting** ``` <?php $gpg = new gnupg(); ?> ``` **Example #4 OO gnupg initializer example with overriden file name and home dir** ``` <?php $gpg = new gnupg(["file_name" => "/usr/bin/gpg2", "home_dir" => "/var/www/.gnupg"]); ?> ``` php imagecolorexact imagecolorexact =============== (PHP 4, PHP 5, PHP 7, PHP 8) imagecolorexact — Get the index of the specified color ### Description ``` imagecolorexact( GdImage $image, int $red, int $green, int $blue ): int ``` Returns the index of the specified color in the palette of the image. If you created the image from a file, only colors used in the image are resolved. Colors present only in the palette are not resolved. ### Parameters `image` A [GdImage](class.gdimage) object, returned by one of the image creation functions, such as [imagecreatetruecolor()](function.imagecreatetruecolor). `red` Value of red component. `green` Value of green component. `blue` Value of blue component. ### Return Values Returns the index of the specified color in the palette, or -1 if the color does not exist. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `image` expects a [GdImage](class.gdimage) instance now; previously, a resource was expected. | ### Examples **Example #1 Get colors from the GD logo** ``` <?php // Setup an image $im = imagecreatefrompng('./gdlogo.png'); $colors   = Array(); $colors[] = imagecolorexact($im, 255, 0, 0); $colors[] = imagecolorexact($im, 0, 0, 0); $colors[] = imagecolorexact($im, 255, 255, 255); $colors[] = imagecolorexact($im, 100, 255, 52); print_r($colors); // Free from memory imagedestroy($im); ?> ``` The above example will output something similar to: ``` Array ( [0] => 16711680 [1] => 0 [2] => 16777215 [3] => 6618932 ) ``` ### See Also * [imagecolorclosest()](function.imagecolorclosest) - Get the index of the closest color to the specified color php Componere\Method::setStatic Componere\Method::setStatic =========================== (Componere 2 >= 2.1.0) Componere\Method::setStatic — Accessibility Modification ### Description ``` public Componere\Method::setStatic(): Method ``` ### Return Values The current Method php imap_listsubscribed imap\_listsubscribed ==================== (PHP 4, PHP 5, PHP 7, PHP 8) imap\_listsubscribed — Alias of [imap\_lsub()](function.imap-lsub) ### Description This function is an alias of: [imap\_lsub()](function.imap-lsub). php pg_get_result pg\_get\_result =============== (PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8) pg\_get\_result — Get asynchronous query result ### Description ``` pg_get_result(PgSql\Connection $connection): PgSql\Result|false ``` **pg\_get\_result()** gets an [PgSql\Result](class.pgsql-result) instance from an asynchronous query executed by [pg\_send\_query()](function.pg-send-query), [pg\_send\_query\_params()](function.pg-send-query-params) or [pg\_send\_execute()](function.pg-send-execute). [pg\_send\_query()](function.pg-send-query) and the other asynchronous query functions can send multiple queries to a PostgreSQL server and **pg\_get\_result()** is used to get each query's results, one by one. ### Parameters `connection` An [PgSql\Connection](class.pgsql-connection) instance. ### Return Values An [PgSql\Result](class.pgsql-result) instance, or **`false`** if no more results are available. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | Returns an [PgSql\Result](class.pgsql-result) instance now; previously, a [resource](language.types.resource) was returned. | | 8.1.0 | The `connection` parameter expects an [PgSql\Connection](class.pgsql-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **pg\_get\_result()** example** ``` <?php   $dbconn = pg_connect("dbname=publisher") or die("Could not connect");   if (!pg_connection_busy($dbconn)) {       pg_send_query($dbconn, "select * from authors; select count(*) from authors;");   }      $res1 = pg_get_result($dbconn);   echo "First call to pg_get_result(): $res1\n";   $rows1 = pg_num_rows($res1);   echo "$res1 has $rows1 records\n\n";      $res2 = pg_get_result($dbconn);   echo "Second call to pg_get_result(): $res2\n";   $rows2 = pg_num_rows($res2);   echo "$res2 has $rows2 records\n"; ?> ``` The above example will output: ``` First call to pg_get_result(): Resource id #3 Resource id #3 has 3 records Second call to pg_get_result(): Resource id #4 Resource id #4 has 1 records ``` ### See Also * [pg\_send\_query()](function.pg-send-query) - Sends asynchronous query php eio_sync eio\_sync ========= (PECL eio >= 0.0.1dev) eio\_sync — Commit buffer cache to disk ### Description ``` eio_sync(int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL): resource ``` ### Parameters This function has no parameters. ### Return Values **eio\_sync()** returns request resource on success, or **`false`** on failure. php rad2deg rad2deg ======= (PHP 4, PHP 5, PHP 7, PHP 8) rad2deg — Converts the radian number to the equivalent number in degrees ### Description ``` rad2deg(float $num): float ``` This function converts `num` from radian to degrees. ### Parameters `num` A radian value ### Return Values The equivalent of `num` in degrees ### Examples **Example #1 **rad2deg()** example** ``` <?php echo rad2deg(M_PI_4); // 45 ?> ``` ### See Also * [deg2rad()](function.deg2rad) - Converts the number in degrees to the radian equivalent php SolrQuery::removeFilterQuery SolrQuery::removeFilterQuery ============================ (PECL solr >= 0.9.2) SolrQuery::removeFilterQuery — Removes a filter query ### Description ``` public SolrQuery::removeFilterQuery(string $fq): SolrQuery ``` Removes a filter query. ### Parameters `fq` The filter query to remove ### Return Values Returns the current SolrQuery object, if the return value is used. php sodium_pad sodium\_pad =========== (PHP 7 >= 7.2.0, PHP 8) sodium\_pad — Add padding data ### Description ``` sodium_pad(string $string, int $block_size): string ``` Right-pad a string to a desired length. Timing-safe. ### Parameters `string` Unpadded string. `block_size` The string will be padded until it is an even multiple of the block size. ### Return Values Padded string. php Threaded::count Threaded::count =============== (PECL pthreads >= 2.0.0) Threaded::count — Manipulation ### Description ``` public Threaded::count(): int ``` Returns the number of properties for this object ### Parameters This function has no parameters. ### Return Values ### Examples **Example #1 Counting the properties of an object** ``` <?php $safe = new Threaded(); while (count($safe) < 10) {     $safe[] = count($safe); } var_dump(count($safe)); ?> ``` The above example will output: ``` int(10) ``` php MultipleIterator::countIterators MultipleIterator::countIterators ================================ (PHP 5 >= 5.3.0, PHP 7, PHP 8) MultipleIterator::countIterators — Gets the number of attached iterator instances ### Description ``` public MultipleIterator::countIterators(): int ``` Gets the number of attached iterator instances. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values The number of attached iterator instances (as an int). ### See Also * [MultipleIterator::containsIterator()](multipleiterator.containsiterator) - Checks if an iterator is attached php fseek fseek ===== (PHP 4, PHP 5, PHP 7, PHP 8) fseek — Seeks on a file pointer ### Description ``` fseek(resource $stream, int $offset, int $whence = SEEK_SET): int ``` Sets the file position indicator for the file referenced by `stream`. The new position, measured in bytes from the beginning of the file, is obtained by adding `offset` to the position specified by `whence`. In general, it is allowed to seek past the end-of-file; if data is then written, reads in any unwritten region between the end-of-file and the sought position will yield bytes with value 0. However, certain streams may not support this behavior, especially when they have an underlying fixed size storage. ### Parameters `stream` A file system pointer resource that is typically created using [fopen()](function.fopen). `offset` The offset. To move to a position before the end-of-file, you need to pass a negative value in `offset` and set `whence` to **`SEEK_END`**. `whence` `whence` values are: * **`SEEK_SET`** - Set position equal to `offset` bytes. * **`SEEK_CUR`** - Set position to current location plus `offset`. * **`SEEK_END`** - Set position to end-of-file plus `offset`. ### Return Values Upon success, returns 0; otherwise, returns -1. ### Examples **Example #1 **fseek()** example** ``` <?php $fp = fopen('somefile.txt', 'r'); // read some data $data = fgets($fp, 4096); // move back to the beginning of the file // same as rewind($fp); fseek($fp, 0); ?> ``` ### Notes > > **Note**: > > > If you have opened the file in append (`a` or `a+`) mode, any data you write to the file will always be appended, regardless of the file position, and the result of calling **fseek()** will be undefined. > > > > **Note**: > > > Not all streams support seeking. For those that do not support seeking, forward seeking from the current position is accomplished by reading and discarding data; other forms of seeking will fail. > > ### See Also * [ftell()](function.ftell) - Returns the current position of the file read/write pointer * [rewind()](function.rewind) - Rewind the position of a file pointer php Imagick::borderImage Imagick::borderImage ==================== (PECL imagick 2, PECL imagick 3) Imagick::borderImage — Surrounds the image with a border ### Description ``` public Imagick::borderImage(mixed $bordercolor, int $width, int $height): bool ``` Surrounds the image with a border of the color defined by the bordercolor ImagickPixel object. ### Parameters `bordercolor` ImagickPixel object or a string containing the border color `width` Border width `height` Border height ### Return Values Returns **`true`** on success. ### Changelog | Version | Description | | --- | --- | | PECL imagick 2.1.0 | Now allows a string representing the color as the first parameter. Previous versions allow only an ImagickPixel object. | ### Examples **Example #1 **Imagick::borderImage()**** ``` <?php function borderImage($imagePath, $color, $width, $height) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->borderImage($color, $width, $height);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php Parle\Stack::pop Parle\Stack::pop ================ (PECL parle >= 0.5.1) Parle\Stack::pop — Pop an item from the stack ### Description ``` public Parle\Stack::pop(): void ``` ### Parameters This function has no parameters. ### Return Values No value is returned. php eio_busy eio\_busy ========= (PECL eio >= 0.0.1dev) eio\_busy — Artificially increase load. Could be useful in tests, benchmarking ### Description ``` eio_busy( int $delay, int $pri = EIO_PRI_DEFAULT, callable $callback = NULL, mixed $data = NULL ): resource ``` **eio\_busy()** artificially increases load taking `delay` seconds to execute. May be used for debugging, or benchmarking. ### Parameters `delay` Delay in seconds `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` This callback is called when all the group requests are done. `data` Arbitrary variable passed to `callback`. ### Return Values **eio\_busy()** returns request resource on success, or **`false`** on failure. ### See Also * [eio\_nop()](function.eio-nop) - Does nothing, except go through the whole request cycle php Ds\Map::keys Ds\Map::keys ============ (PECL ds >= 1.0.0) Ds\Map::keys — Returns a set of the map's keys ### Description ``` public Ds\Map::keys(): Ds\Set ``` Returns a set containing all the keys of the map, in the same order. ### Parameters This function has no parameters. ### Return Values A **Ds\Set** containing all the keys of the map. ### Examples **Example #1 **Ds\Map::keys()** example** ``` <?php $map = new \Ds\Map(["a" => 1, "b" => 2, "c" => 3]); var_dump($map->keys()); ?> ``` The above example will output something similar to: ``` object(Ds\Set)#2 (3) { [0]=> string(1) "a" [1]=> string(1) "b" [2]=> string(1) "c" } ``` php ImagickKernel::addKernel ImagickKernel::addKernel ======================== (PECL imagick >= 3.3.0) ImagickKernel::addKernel — Description ### Description ``` public ImagickKernel::addKernel(ImagickKernel $ImagickKernel): void ``` Attach another kernel to this kernel to allow them to both be applied in a single morphology or filter function. Returns the new combined kernel. ### Parameters `ImagickKernel` ### Return Values ### Examples **Example #1 **ImagickKernel::addKernel()**** ``` <?php function addKernel($imagePath) {     $matrix1 = [         [-1, -1, -1],         [ 0,  0,  0],         [ 1,  1,  1],     ];     $matrix2 = [         [-1,  0,  1],         [-1,  0,  1],         [-1,  0,  1],     ];     $kernel1 = ImagickKernel::fromMatrix($matrix1);     $kernel2 = ImagickKernel::fromMatrix($matrix2);     $kernel1->addKernel($kernel2);     $imagick = new \Imagick(realpath($imagePath));     $imagick->filter($kernel1);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` php None Properties ---------- Class member variables are called *properties*. They may be referred to using other terms such as *fields*, but for the purposes of this reference *properties* will be used. They are defined by using at least one modifier (such as [Visibility](language.oop5.visibility), [Static Keyword](language.oop5.static), or, as of PHP 8.1.0, [readonly](language.oop5.properties#language.oop5.properties.readonly-properties)), optionally (except for `readonly` properties), as of PHP 7.4, followed by a type declaration, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a [constant](language.constants) value. > > **Note**: > > > An obsolete way of declaring class properties, is by using the `var` keyword instead of a modifier. > > > **Note**: A property declared without a [Visibility](language.oop5.visibility) modifier will be declared as `public`. > > Within class methods non-static properties may be accessed by using `->` (Object Operator): $this->property (where `property` is the name of the property). Static properties are accessed by using the `::` (Double Colon): self::$property. See [Static Keyword](language.oop5.static) for more information on the difference between static and non-static properties. The pseudo-variable $this is available inside any class method when that method is called from within an object context. $this is the value of the calling object. **Example #1 Property declarations** ``` <?php class SimpleClass {    public $var1 = 'hello ' . 'world';    public $var2 = <<<EOD hello world EOD;    public $var3 = 1+2;    // invalid property declarations:    public $var4 = self::myStaticMethod();    public $var5 = $myVar;    // valid property declarations:    public $var6 = myConstant;    public $var7 = [true, false];    public $var8 = <<<'EOD' hello world EOD;    // Without visibility modifier:    static $var9;    readonly int $var10; } ?> ``` > > **Note**: > > > There are various functions to handle classes and objects. See the [Class/Object Functions](https://www.php.net/manual/en/ref.classobj.php) reference. > > ### Type declarations As of PHP 7.4.0, property definitions can include [Type declarations](language.types.declarations), with the exception of [callable](language.types.callable). **Example #2 Example of typed properties** ``` <?php class User {     public int $id;     public ?string $name;     public function __construct(int $id, ?string $name)     {         $this->id = $id;         $this->name = $name;     } } $user = new User(1234, null); var_dump($user->id); var_dump($user->name); ?> ``` The above example will output: ``` int(1234) NULL ``` Typed properties must be initialized before accessing, otherwise an [Error](class.error) is thrown. **Example #3 Accessing properties** ``` <?php class Shape {     public int $numberOfSides;     public string $name;     public function setNumberOfSides(int $numberOfSides): void     {         $this->numberOfSides = $numberOfSides;     }     public function setName(string $name): void     {         $this->name = $name;     }     public function getNumberOfSides(): int     {         return $this->numberOfSides;     }     public function getName(): string     {         return $this->name;     } } $triangle = new Shape(); $triangle->setName("triangle"); $triangle->setNumberofSides(3); var_dump($triangle->getName()); var_dump($triangle->getNumberOfSides()); $circle = new Shape(); $circle->setName("circle"); var_dump($circle->getName()); var_dump($circle->getNumberOfSides()); ?> ``` The above example will output: ``` string(8) "triangle" int(3) string(6) "circle" Fatal error: Uncaught Error: Typed property Shape::$numberOfSides must not be accessed before initialization ``` ### Readonly properties As of PHP 8.1.0, a property can be declared with the `readonly` modifier, which prevents modification of the property after initialization. **Example #4 Example of readonly properties** ``` <?php class Test {    public readonly string $prop;    public function __construct(string $prop) {        // Legal initialization.        $this->prop = $prop;    } } $test = new Test("foobar"); // Legal read. var_dump($test->prop); // string(6) "foobar" // Illegal reassignment. It does not matter that the assigned value is the same. $test->prop = "foobar"; // Error: Cannot modify readonly property Test::$prop ?> ``` > > **Note**: > > > The readonly modifier can only be applied to [typed properties](language.oop5.properties#language.oop5.properties.typed-properties). A readonly property without type constraints can be created using the [Mixed](language.types.mixed) type. > > > > **Note**: > > > Readonly static properties are not supported. > > A readonly property can only be initialized once, and only from the scope where it has been declared. Any other assignment or modification of the property will result in an [Error](class.error) exception. **Example #5 Illegal initialization of readonly properties** ``` <?php class Test1 {     public readonly string $prop; } $test1 = new Test1; // Illegal initialization outside of private scope. $test1->prop = "foobar"; // Error: Cannot initialize readonly property Test1::$prop from global scope ?> ``` > > **Note**: > > > Specifying an explicit default value on readonly properties is not allowed, because a readonly property with a default value is essentially the same as a constant, and thus not particularly useful. > > > > ``` > <?php > > class Test { >     // Fatal error: Readonly property Test::$prop cannot have default value >     public readonly int $prop = 42; > } > ?> > ``` > > > **Note**: > > > Readonly properties cannot be [unset()](function.unset) once they are initialized. However, it is possible to unset a readonly property prior to initialization, from the scope where the property has been declared. > > Modifications are not necessarily plain assignments, all of the following will also result in an [Error](class.error) exception: ``` <?php class Test {     public function __construct(         public readonly int $i = 0,         public readonly array $ary = [],     ) {} } $test = new Test; $test->i += 1; $test->i++; ++$test->i; $test->ary[] = 1; $test->ary[0][] = 1; $ref =& $test->i; $test->i =& $ref; byRef($test->i); foreach ($test as &$prop); ?> ``` However, readonly properties do not preclude interior mutability. Objects (or resources) stored in readonly properties may still be modified internally: ``` <?php class Test {     public function __construct(public readonly object $obj) {} } $test = new Test(new stdClass); // Legal interior mutation. $test->obj->foo = 1; // Illegal reassignment. $test->obj = new stdClass; ?> ``` ### Dynamic properties If trying to assign to a non-existent property on an object, PHP will automatically create a corresponding property. This dynamically created property will *only* be available on this class instance. **Warning** Dynamic properties are deprecated as of PHP 8.2.0. It is recommended to declare the property instead. To handle arbitrary property names, the class should implement the magic methods [\_\_get()](language.oop5.overloading#object.get) and [\_\_set()](language.oop5.overloading#object.set). At last resort the class can be marked with the `#[\AllowDynamicProperties]` attribute.
programming_docs
php runkit7_zval_inspect runkit7\_zval\_inspect ====================== (PECL runkit7 >= Unknown) runkit7\_zval\_inspect — Returns information about the passed in value with data types, reference counts, etc ### Description ``` runkit7_zval_inspect(string $value): array ``` ### Parameters `value` The value to return the representation of ### Return Values The array returned by this function contains the following elements: * `address` * `refcount` (optional) * `is_ref` (optional) * `type` ### Examples **Example #1 **runkit7\_zval\_inspect()** example** ``` <?php $var = new DateTime(); var_dump(runkit7_zval_inspect($var)); $var = 1; var_dump(runkit7_zval_inspect($var)); ?> ``` The above example will output: ``` array(4) { ["address"]=> string(14) "0x7f45ab21b1e0" ["refcount"]=> int(2) ["is_ref"]=> bool(false) ["type"]=> int(8) } array(2) { ["address"]=> string(14) "0x7f45ab21b1e0" ["type"]=> int(4) } ``` ### See Also * [References Explained](https://www.php.net/manual/en/language.references.php) * [» References Explained (by Derick Rethans)](http://derickrethans.nl/php_references_article.php) php RecursiveTreeIterator::nextElement RecursiveTreeIterator::nextElement ================================== (PHP 5 >= 5.3.0, PHP 7, PHP 8) RecursiveTreeIterator::nextElement — Next element ### Description ``` public RecursiveTreeIterator::nextElement(): void ``` Called when the next element is available. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php apache_note apache\_note ============ (PHP 4, PHP 5, PHP 7, PHP 8) apache\_note — Get and set apache request notes ### Description ``` apache_note(string $note_name, ?string $note_value = null): string|false ``` This function is a wrapper for Apache's `table_get` and `table_set`. It edits the table of notes that exists during a request. The table's purpose is to allow Apache modules to communicate. The main use for **apache\_note()** is to pass information from one module to another within the same request. ### Parameters `note_name` The name of the note. `note_value` The value of the note. ### Return Values If `note_value` is omitted or **`null`**, it returns the current value of note `note_name`. Otherwise, it sets the value of note `note_name` to `note_value` and returns the previous value of note `note_name`. If the note cannot be retrieved, **`false`** is returned. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `note_value` is nullable now. | ### Examples **Example #1 Passing information between PHP and Perl** ``` <?php apache_note('name', 'Fredrik Ekengren'); // Call perl script virtual("/perl/some_script.pl"); $result = apache_note("resultdata"); ?> ``` ``` # Get Apache request object my $r = Apache->request()->main(); # Get passed data my $name = $r->notes('name'); # some processing # Pass result back to PHP $r->notes('resultdata', $result); ``` **Example #2 Logging values in access.log** ``` <?php apache_note('sessionID', session_id()); ?> ``` ``` # "%{sessionID}n" can be used in the LogFormat directive ``` ### See Also * [virtual()](function.virtual) - Perform an Apache sub-request php sodium_crypto_aead_xchacha20poly1305_ietf_encrypt sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_encrypt ====================================================== (PHP 7 >= 7.2.0, PHP 8) sodium\_crypto\_aead\_xchacha20poly1305\_ietf\_encrypt — (Preferred) Encrypt then authenticate with XChaCha20-Poly1305 ### Description ``` sodium_crypto_aead_xchacha20poly1305_ietf_encrypt( string $message, string $additional_data, string $nonce, string $key ): string ``` Encrypt then authenticate with XChaCha20-Poly1305 (eXtended-nonce variant). Generally, XChaCha20-Poly1305 is the best of the provided AEAD modes to use. ### Parameters `message` The plaintext message to encrypt. `additional_data` Additional, authenticated data. This is used in the verification of the authentication tag appended to the ciphertext, but it is not encrypted or stored in the ciphertext. `nonce` A number that must be only used once, per message. 24 bytes long. This is a large enough bound to generate randomly (i.e. [random\_bytes()](https://www.php.net/manual/en/function.random-bytes.php)). `key` Encryption key (256-bit). ### Return Values Returns the ciphertext and tag on success, or **`false`** on failure. php IntlChar::getPropertyName IntlChar::getPropertyName ========================= (PHP 7, PHP 8) IntlChar::getPropertyName — Get the Unicode name for a property ### Description ``` public static IntlChar::getPropertyName(int $property, int $type = IntlChar::LONG_PROPERTY_NAME): string|false ``` Returns the Unicode name for a given property, as given in the Unicode database file PropertyAliases.txt. In addition, this function maps the property **`IntlChar::PROPERTY_GENERAL_CATEGORY_MASK`** to the synthetic names "gcm" / "General\_Category\_Mask". These names are not in PropertyAliases.txt. This function complements [IntlChar::getPropertyEnum()](intlchar.getpropertyenum). ### Parameters `property` The Unicode property to lookup (see the `IntlChar::PROPERTY_*` constants). **`IntlChar::PROPERTY_INVALID_CODE`** should not be used. Also, if `property` is out of range, **`false`** is returned. `type` Selector for which name to get. If out of range, **`false`** is returned. All properties have a long name. Most have a short name, but some do not. Unicode allows for additional names; if present these will be returned by adding 1, 2, etc. to **`IntlChar::LONG_PROPERTY_NAME`**. ### Return Values Returns the name, or **`false`** if either the `property` or the `type` is out of range. If a given `type` returns **`false`**, then all larger values of `type` will return **`false`**, with one exception: if **`false`** is returned for **`IntlChar::SHORT_PROPERTY_NAME`**, then **`IntlChar::LONG_PROPERTY_NAME`** (and higher) may still return a non-**`false`** value. ### Examples **Example #1 Testing different properties** ``` <?php var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS)); var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::SHORT_PROPERTY_NAME)); var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME)); var_dump(IntlChar::getPropertyName(IntlChar::PROPERTY_BIDI_CLASS, IntlChar::LONG_PROPERTY_NAME + 1)); ?> ``` The above example will output: ``` string(10) "Bidi_Class" string(2) "bc" string(10) "Bidi_Class" bool(false) ``` ### See Also * [IntlChar::getPropertyEnum()](intlchar.getpropertyenum) - Get the property constant value for a given property name php PhpToken::__toString PhpToken::\_\_toString ====================== (PHP 8) PhpToken::\_\_toString — Returns the textual content of the token. ### Description ``` public PhpToken::__toString(): string ``` Returns the textual content of the token. ### Parameters This function has no parameters. ### Return Values A textual content of the token. ### Examples **Example #1 **PhpToken::\_\_toString()** example** ``` <?php $token = new PhpToken(T_ECHO, 'echo'); echo $token; ``` The above examples will output: ``` echo ``` ### See Also * [token\_name()](function.token-name) - Get the symbolic name of a given PHP token php The SoapClient class The SoapClient class ==================== Introduction ------------ (PHP 5, PHP 7, PHP 8) The SoapClient class provides a client for [» SOAP 1.1](http://www.w3.org/TR/soap11/), [» SOAP 1.2](http://www.w3.org/TR/soap12/) servers. It can be used in WSDL or non-WSDL mode. Class synopsis -------------- class **SoapClient** { /\* Properties \*/ private ?string [$uri](class.soapclient#soapclient.props.uri) = null; private ?int [$style](class.soapclient#soapclient.props.style) = null; private ?int [$use](class.soapclient#soapclient.props.use) = null; private ?string [$location](class.soapclient#soapclient.props.location) = null; private bool [$trace](class.soapclient#soapclient.props.trace) = false; private ?int [$compression](class.soapclient#soapclient.props.compression) = null; private ?resource [$sdl](class.soapclient#soapclient.props.sdl) = null; private ?resource [$typemap](class.soapclient#soapclient.props.typemap) = null; private ?resource [$httpsocket](class.soapclient#soapclient.props.httpsocket) = null; private ?resource [$httpurl](class.soapclient#soapclient.props.httpurl) = null; private ?string [$\_login](class.soapclient#soapclient.props.-login) = null; private ?string [$\_password](class.soapclient#soapclient.props.-password) = null; private bool [$\_use\_digest](class.soapclient#soapclient.props.-use-digest) = false; private ?string [$\_digest](class.soapclient#soapclient.props.-digest) = null; private ?string [$\_proxy\_host](class.soapclient#soapclient.props.-proxy-host) = null; private ?int [$\_proxy\_port](class.soapclient#soapclient.props.-proxy-port) = null; private ?string [$\_proxy\_login](class.soapclient#soapclient.props.-proxy-login) = null; private ?string [$\_proxy\_password](class.soapclient#soapclient.props.-proxy-password) = null; private bool [$\_exceptions](class.soapclient#soapclient.props.-exceptions) = true; private ?string [$\_encoding](class.soapclient#soapclient.props.-encoding) = null; private ?array [$\_classmap](class.soapclient#soapclient.props.-classmap) = null; private ?int [$\_features](class.soapclient#soapclient.props.-features) = null; private int [$\_connection\_timeout](class.soapclient#soapclient.props.-connection-timeout); private ?resource [$\_stream\_context](class.soapclient#soapclient.props.-stream-context) = null; private ?string [$\_user\_agent](class.soapclient#soapclient.props.-user-agent) = null; private bool [$\_keep\_alive](class.soapclient#soapclient.props.-keep-alive) = true; private ?int [$\_ssl\_method](class.soapclient#soapclient.props.-ssl-method) = null; private int [$\_soap\_version](class.soapclient#soapclient.props.-soap-version); private ?int [$\_use\_proxy](class.soapclient#soapclient.props.-use-proxy) = null; private array [$\_cookies](class.soapclient#soapclient.props.-cookies) = []; private ?array [$\_\_default\_headers](class.soapclient#soapclient.props.--default-headers) = null; private ?[SoapFault](class.soapfault) [$\_\_soap\_fault](class.soapclient#soapclient.props.--soap-fault) = null; private ?string [$\_\_last\_request](class.soapclient#soapclient.props.--last-request) = null; private ?string [$\_\_last\_response](class.soapclient#soapclient.props.--last-response) = null; private ?string [$\_\_last\_request\_headers](class.soapclient#soapclient.props.--last-request-headers) = null; private ?string [$\_\_last\_response\_headers](class.soapclient#soapclient.props.--last-response-headers) = null; /\* Methods \*/ public [\_\_construct](soapclient.construct)(?string `$wsdl`, array `$options` = []) ``` public __call(string $name, array $args): mixed ``` ``` public __doRequest( string $request, string $location, string $action, int $version, bool $oneWay = false ): ?string ``` ``` public __getCookies(): array ``` ``` public __getFunctions(): ?array ``` ``` public __getLastRequest(): ?string ``` ``` public __getLastRequestHeaders(): ?string ``` ``` public __getLastResponse(): ?string ``` ``` public __getLastResponseHeaders(): ?string ``` ``` public __getTypes(): ?array ``` ``` public __setCookie(string $name, ?string $value = null): void ``` ``` public __setLocation(?string $location = null): ?string ``` ``` public __setSoapHeaders(SoapHeader|array|null $headers = null): bool ``` ``` public __soapCall( string $name, array $args, ?array $options = null, SoapHeader|array|null $inputHeaders = null, array &$outputHeaders = null ): mixed ``` } Properties ---------- \_\_default\_headers \_\_last\_request \_\_last\_request\_headers \_\_last\_response \_\_last\_response\_headers \_\_soap\_fault \_classmap \_connection\_timeout \_cookies \_digest \_encoding \_exceptions \_features \_keep\_alive \_login \_password \_proxy\_host \_proxy\_login \_proxy\_password \_proxy\_port \_soap\_version \_ssl\_method \_stream\_context \_use\_digest \_use\_proxy \_user\_agent compression httpsocket httpurl location sdl style trace typemap uri use Table of Contents ----------------- * [SoapClient::\_\_call](soapclient.call) — Calls a SOAP function (deprecated) * [SoapClient::\_\_construct](soapclient.construct) — SoapClient constructor * [SoapClient::\_\_doRequest](soapclient.dorequest) — Performs a SOAP request * [SoapClient::\_\_getCookies](soapclient.getcookies) — Get list of cookies * [SoapClient::\_\_getFunctions](soapclient.getfunctions) — Returns list of available SOAP functions * [SoapClient::\_\_getLastRequest](soapclient.getlastrequest) — Returns last SOAP request * [SoapClient::\_\_getLastRequestHeaders](soapclient.getlastrequestheaders) — Returns the SOAP headers from the last request * [SoapClient::\_\_getLastResponse](soapclient.getlastresponse) — Returns last SOAP response * [SoapClient::\_\_getLastResponseHeaders](soapclient.getlastresponseheaders) — Returns the SOAP headers from the last response * [SoapClient::\_\_getTypes](soapclient.gettypes) — Returns a list of SOAP types * [SoapClient::\_\_setCookie](soapclient.setcookie) — Defines a cookie for SOAP requests * [SoapClient::\_\_setLocation](soapclient.setlocation) — Sets the location of the Web service to use * [SoapClient::\_\_setSoapHeaders](soapclient.setsoapheaders) — Sets SOAP headers for subsequent calls * [SoapClient::\_\_soapCall](soapclient.soapcall) — Calls a SOAP function php ReflectionFunction::invoke ReflectionFunction::invoke ========================== (PHP 5, PHP 7, PHP 8) ReflectionFunction::invoke — Invokes function ### Description ``` public ReflectionFunction::invoke(mixed ...$args): mixed ``` Invokes a reflected function. ### Parameters `args` The passed in argument list. It accepts a variable number of arguments which are passed to the function much like [call\_user\_func()](function.call-user-func) is. ### Return Values Returns the result of the invoked function call. ### Examples **Example #1 **ReflectionFunction::invoke()** example** ``` <?php function title($title, $name) {     return sprintf("%s. %s\r\n", $title, $name); } $function = new ReflectionFunction('title'); echo $function->invoke('Dr', 'Phil'); ?> ``` The above example will output: ``` Dr. Phil ``` ### Notes > > **Note**: > > > **ReflectionFunction::invoke()** cannot be used when reference parameters are expected. [ReflectionFunction::invokeArgs()](reflectionfunction.invokeargs) has to be used instead (passing references in the argument list). > > ### See Also * [ReflectionFunction::export()](reflectionfunction.export) - Exports function * [\_\_invoke()](language.oop5.magic#object.invoke) * [call\_user\_func()](function.call-user-func) - Call the callback given by the first parameter php ZipArchive::getStreamIndex ZipArchive::getStreamIndex ========================== (PHP 8 >= 8.2.0, PECL zip >= 1.20.0) ZipArchive::getStreamIndex — Get a file handler to the entry defined by its index (read only) ### Description ``` public ZipArchive::getStreamIndex(int $index, int $flags = 0): resource|false ``` Get a file handler to the entry defined by its index. For now, it only supports read operations. ### Parameters `index` Index of the entry `flags` If flags is set to **`ZipArchive::FL_UNCHANGED`**, the original unchanged stream is returned. ### Return Values Returns a file pointer (resource) on success or **`false`** on failure. ### Examples **Example #1 Get the entry contents with [fread()](function.fread) and store it** ``` <?php $contents = ''; $z = new ZipArchive(); if ($z->open('test.zip')) {     $fp = $z->getStreamIndex(1, ZipArchive::FL_UNCHANGED);     if(!$fp) die($z->getStatusString());     echo stream_get_contents($fp);     fclose($fp); } ?> ``` ### See Also * [ZipArchive::getStreamName()](ziparchive.getstreamname) - Get a file handler to the entry defined by its name (read only) php DOMElement::getElementsByTagName DOMElement::getElementsByTagName ================================ (PHP 5, PHP 7, PHP 8) DOMElement::getElementsByTagName — Gets elements by tagname ### Description ``` public DOMElement::getElementsByTagName(string $qualifiedName): DOMNodeList ``` This function returns a new instance of the class [DOMNodeList](class.domnodelist) of all descendant elements with a given tag `qualifiedName`, in the order in which they are encountered in a preorder traversal of this element tree. ### Parameters `qualifiedName` The tag name. Use `*` to return all elements within the element tree. ### Return Values This function returns a new instance of the class [DOMNodeList](class.domnodelist) of all matched elements. ### See Also * [DOMElement::getElementsByTagNameNS()](domelement.getelementsbytagnamens) - Get elements by namespaceURI and localName php ImagickDraw::getStrokeOpacity ImagickDraw::getStrokeOpacity ============================= (PECL imagick 2, PECL imagick 3) ImagickDraw::getStrokeOpacity — Returns the opacity of stroked object outlines ### Description ``` public ImagickDraw::getStrokeOpacity(): float ``` **Warning**This function is currently not documented; only its argument list is available. Returns the opacity of stroked object outlines. ### Return Values Returns a float describing the opacity. php mysqli_stmt::bind_result mysqli\_stmt::bind\_result ========================== mysqli\_stmt\_bind\_result ========================== (PHP 5, PHP 7, PHP 8) mysqli\_stmt::bind\_result -- mysqli\_stmt\_bind\_result — Binds variables to a prepared statement for result storage ### Description Object-oriented style ``` public mysqli_stmt::bind_result(mixed &$var, mixed &...$vars): bool ``` Procedural style ``` mysqli_stmt_bind_result(mysqli_stmt $statement, mixed &$var, mixed &...$vars): bool ``` Binds columns in the result set to variables. When [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) is called to fetch data, the MySQL client/server protocol places the data for the bound columns into the specified variables `var`/`vars`. A column can be bound or rebound at any time, even after a result set has been partially retrieved. The new binding takes effect the next time [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) is called. > > **Note**: > > > All columns must be bound after [mysqli\_stmt\_execute()](mysqli-stmt.execute) and prior to calling [mysqli\_stmt\_fetch()](mysqli-stmt.fetch). > > > > **Note**: > > > Depending on column types bound variables can silently change to the corresponding PHP type. > > **Tip** This functions is useful for simple results. To retrieve iterable result set, or fetch each row as an array or object, use [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result). ### Parameters `statement` Procedural style only: A [mysqli\_stmt](class.mysqli-stmt) object returned by [mysqli\_stmt\_init()](mysqli.stmt-init). `var` The first variable to be bound. `vars` Further variables to be bound. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Object-oriented style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $mysqli = new mysqli("localhost", "my_user", "my_password", "world"); /* prepare statement */ $stmt = $mysqli->prepare("SELECT Code, Name FROM Country ORDER BY Name LIMIT 5"); $stmt->execute(); /* bind variables to prepared statement */ $stmt->bind_result($col1, $col2); /* fetch values */ while ($stmt->fetch()) {     printf("%s %s\n", $col1, $col2); } ``` **Example #2 Procedural style** ``` <?php mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT); $link = mysqli_connect("localhost", "my_user", "my_password", "world"); /* prepare statement */ $stmt = mysqli_prepare($link, "SELECT Code, Name FROM Country ORDER BY Name LIMIT 5"); mysqli_stmt_execute($stmt); /* bind variables to prepared statement */ mysqli_stmt_bind_result($stmt, $col1, $col2); /* fetch values */ while (mysqli_stmt_fetch($stmt)) {     printf("%s %s\n", $col1, $col2); } ``` The above examples will output something similar to: ``` AFG Afghanistan ALB Albania DZA Algeria ASM American Samoa AND Andorra ``` ### See Also * [mysqli\_stmt\_get\_result()](mysqli-stmt.get-result) - Gets a result set from a prepared statement as a mysqli\_result object * [mysqli\_stmt\_bind\_param()](mysqli-stmt.bind-param) - Binds variables to a prepared statement as parameters * [mysqli\_stmt\_execute()](mysqli-stmt.execute) - Executes a prepared statement * [mysqli\_stmt\_fetch()](mysqli-stmt.fetch) - Fetch results from a prepared statement into the bound variables * [mysqli\_prepare()](mysqli.prepare) - Prepares an SQL statement for execution * [mysqli\_stmt\_prepare()](mysqli-stmt.prepare) - Prepares an SQL statement for execution
programming_docs
php list list ==== (PHP 4, PHP 5, PHP 7, PHP 8) list — Assign variables as if they were an array ### Description ``` list(mixed $var, mixed ...$vars = ?): array ``` Like [array()](function.array), this is not really a function, but a language construct. **list()** is used to assign a list of variables in one operation. Strings can not be unpacked and **list()** expressions can not be completely empty. > > **Note**: > > > Before PHP 7.1.0, **list()** only worked on numerical arrays and assumes the numerical indices start at 0. > > ### Parameters `var` A variable. `vars` Further variables. ### Return Values Returns the assigned array. ### Changelog | Version | Description | | --- | --- | | 7.3.0 | Support for reference assignments in array destructuring was added. | | 7.1.0 | It is now possible to specify keys in **list()**. This enables destructuring of arrays with non-integer or non-sequential keys. | ### Examples **Example #1 **list()** examples** ``` <?php $info = array('coffee', 'brown', 'caffeine'); // Listing all the variables list($drink, $color, $power) = $info; echo "$drink is $color and $power makes it special.\n"; // Listing some of them list($drink, , $power) = $info; echo "$drink has $power.\n"; // Or let's skip to only the third one list( , , $power) = $info; echo "I need $power!\n"; // list() doesn't work with strings list($bar) = "abcde"; var_dump($bar); // NULL ?> ``` **Example #2 An example use of **list()**** ``` <?php $result = $pdo->query("SELECT id, name FROM employees"); while (list($id, $name) = $result->fetch(PDO::FETCH_NUM)) {     echo "id: $id, name: $name\n"; } ?> ``` **Example #3 Using nested **list()**** ``` <?php list($a, list($b, $c)) = array(1, array(2, 3)); var_dump($a, $b, $c); ?> ``` ``` int(1) int(2) int(3) ``` **Example #4 **list()** and order of index definitions** The order in which the indices of the array to be consumed by **list()** are defined is irrelevant. ``` <?php $foo = array(2 => 'a', 'foo' => 'b', 0 => 'c'); $foo[1] = 'd'; list($x, $y, $z) = $foo; var_dump($foo, $x, $y, $z); ``` Gives the following output (note the order of the elements compared in which order they were written in the **list()** syntax): ``` array(4) { [2]=> string(1) "a" ["foo"]=> string(1) "b" [0]=> string(1) "c" [1]=> string(1) "d" } string(1) "c" string(1) "d" string(1) "a" ``` **Example #5 **list()** with keys** As of PHP 7.1.0 **list()** can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed. ``` <?php $data = [     ["id" => 1, "name" => 'Tom'],     ["id" => 2, "name" => 'Fred'], ]; foreach ($data as ["id" => $id, "name" => $name]) {     echo "id: $id, name: $name\n"; } echo PHP_EOL; list(1 => $second, 3 => $fourth) = [1, 2, 3, 4]; echo "$second, $fourth\n"; ``` The above example will output: ``` id: 1, name: Tom id: 2, name: Fred 2, 4 ``` ### See Also * [each()](function.each) - Return the current key and value pair from an array and advance the array cursor * [array()](function.array) - Create an array * [extract()](function.extract) - Import variables into the current symbol table from an array php eio_fstat eio\_fstat ========== (PECL eio >= 0.0.1dev) eio\_fstat — Get file status ### Description ``` eio_fstat( mixed $fd, int $pri, callable $callback, mixed $data = ? ): resource ``` **eio\_fstat()** returns file status information in `result` argument of `callback` ### Parameters `fd` Stream, Socket resource, or numeric file descriptor. `pri` The request priority: **`EIO_PRI_DEFAULT`**, **`EIO_PRI_MIN`**, **`EIO_PRI_MAX`**, or **`null`**. If **`null`** passed, `pri` internally is set to **`EIO_PRI_DEFAULT`**. `callback` `callback` function is called when the request is done. It should match the following prototype: ``` void callback(mixed $data, int $result[, resource $req]); ``` `data` is custom data passed to the request. `result` request-specific result value; basically, the value returned by corresponding system call. `req` is optional request resource which can be used with functions like [eio\_get\_last\_error()](function.eio-get-last-error) `data` Arbitrary variable passed to `callback`. ### Return Values [eio\_busy()](function.eio-busy) returns request resource on success, or **`false`** on failure. ### Examples **Example #1 [eio\_lstat()](function.eio-lstat) example** ``` <?php // Create temporary file $tmp_filename = dirname(__FILE__) ."/eio-file.tmp"; touch($tmp_filename); /* Is called when eio_fstat() done */ function my_res_cb($data, $result) {  // Should output array with stat info  var_dump($result);  if ($data['fd']) {   // Close temporary file   eio_close($data['fd']);   eio_event_loop();  }  // Remove temporary file  @unlink($data['file']); } /* Is called when eio_open() done */ function my_open_cb($data, $result) {  // Prepare data for callback  $d = array(   'fd'  => $result,   'file'=> $data  );  // Request stat info  eio_fstat($result, EIO_PRI_DEFAULT, "my_res_cb", $d);  // Process request(s)  eio_event_loop(); } // Open temporary file eio_open($tmp_filename, EIO_O_RDONLY, NULL, EIO_PRI_DEFAULT,   "my_open_cb", $tmp_filename); eio_event_loop(); ?> ``` The above example will output something similar to: ``` array(12) { ["st_dev"]=> int(2050) ["st_ino"]=> int(2489159) ["st_mode"]=> int(33188) ["st_nlink"]=> int(1) ["st_uid"]=> int(1000) ["st_gid"]=> int(100) ["st_rdev"]=> int(0) ["st_blksize"]=> int(4096) ["st_blocks"]=> int(0) ["st_atime"]=> int(1318239506) ["st_mtime"]=> int(1318239506) ["st_ctime"]=> int(1318239506) } ``` ### See Also * [eio\_lstat()](function.eio-lstat) - Get file status * [eio\_stat()](function.eio-stat) - Get file status php DOMImplementation::hasFeature DOMImplementation::hasFeature ============================= (PHP 5, PHP 7, PHP 8) DOMImplementation::hasFeature — Test if the DOM implementation implements a specific feature ### Description ``` public DOMImplementation::hasFeature(string $feature, string $version): bool ``` Test if the DOM implementation implements a specific `feature`. You can find a list of all features in the [» Conformance](http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/introduction.html#ID-Conformance) section of the DOM specification. ### Parameters `feature` The feature to test. `version` The version number of the `feature` to test. In level 2, this can be either `2.0` or `1.0`. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Errors/Exceptions Prior to PHP 8.0.0 this method *could* be called statically, but would issue an **`E_DEPRECATED`** error. As of PHP 8.0.0 calling this method statically throws an [Error](class.error) exception ### Examples **Example #1 Testing your DOM Implementation** ``` <?php $features = array(   'Core'           => 'Core module',   'XML'            => 'XML module',   'HTML'           => 'HTML module',   'Views'          => 'Views module',   'Stylesheets'    => 'Style Sheets module',   'CSS'            => 'CSS module',   'CSS2'           => 'CSS2 module',   'Events'         => 'Events module',   'UIEvents'       => 'User interface Events module',   'MouseEvents'    => 'Mouse Events module',   'MutationEvents' => 'Mutation Events module',   'HTMLEvents'     => 'HTML Events module',   'Range'          => 'Range module',   'Traversal'      => 'Traversal module' );                 foreach ($features as $key => $name) {   if (DOMImplementation::hasFeature($key, '2.0')) {     echo "Has feature $name\n";   } else {     echo "Missing feature $name\n";   } } ?> ``` ### See Also * [DOMNode::isSupported()](domnode.issupported) - Checks if feature is supported for specified version php SplSubject::notify SplSubject::notify ================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) SplSubject::notify — Notify an observer ### Description ``` public SplSubject::notify(): void ``` Notifies all attached observers. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values No value is returned. php eio_set_min_parallel eio\_set\_min\_parallel ======================= (PECL eio >= 0.0.1dev) eio\_set\_min\_parallel — Set minimum parallel thread number ### Description ``` eio_set_min_parallel(string $nthreads): void ``` ### Parameters `nthreads` Number of parallel threads. ### Return Values No value is returned. ### See Also * [eio\_nthreads()](function.eio-nthreads) - Returns number of threads currently in use * [eio\_set\_max\_idle()](function.eio-set-max-idle) - Set maximum number of idle threads * [eio\_set\_max\_parallel()](function.eio-set-max-parallel) - Set maximum parallel threads php HashContext::__construct HashContext::\_\_construct ========================== (PHP 7 >= 7.2.0, PHP 8) HashContext::\_\_construct — Private constructor to disallow direct instantiation ### Description private **HashContext::\_\_construct**() ### Parameters This function has no parameters. php Componere\Abstract\Definition::addTrait Componere\Abstract\Definition::addTrait ======================================= (Componere 2 >= 2.1.0) Componere\Abstract\Definition::addTrait — Add Trait ### Description ``` public Componere\Abstract\Definition::addTrait(string $trait): Definition ``` Shall use the given trait for the current definition ### Parameters `trait` The case insensitive name of a trait ### Return Values The current Definition ### Exceptions **Warning** Shall throw [RuntimeException](class.runtimeexception) if Definition was registered php RecursiveIteratorIterator::getSubIterator RecursiveIteratorIterator::getSubIterator ========================================= (PHP 5, PHP 7, PHP 8) RecursiveIteratorIterator::getSubIterator — The current active sub iterator ### Description ``` public RecursiveIteratorIterator::getSubIterator(?int $level = null): ?RecursiveIterator ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters `level` ### Return Values The current active sub iterator on success; **`null`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `level` is now nullable. | php Memcached::setOption Memcached::setOption ==================== (PECL memcached >= 0.1.0) Memcached::setOption — Set a Memcached option ### Description ``` public Memcached::setOption(int $option, mixed $value): bool ``` This method sets the value of a Memcached `option`. Some options correspond to the ones defined by libmemcached, and some are specific to the extension. ### Parameters `option` One of the `Memcached::OPT_*` constant. See [Memcached Constants](https://www.php.net/manual/en/memcached.constants.php) for more information. `value` The value to be set. > > **Note**: > > > The options listed below require values specified via constants. > > > * `Memcached::OPT_HASH` requires `Memcached::HASH_*` values. > * `Memcached::OPT_DISTRIBUTION` requires `Memcached::DISTRIBUTION_*` values. > > ### Return Values Returns **`true`** on success or **`false`** on failure. ### Examples **Example #1 Setting a Memcached option** ``` <?php $m = new Memcached(); var_dump($m->getOption(Memcached::OPT_HASH) == Memcached::HASH_DEFAULT); $m->setOption(Memcached::OPT_HASH, Memcached::HASH_MURMUR); $m->setOption(Memcached::OPT_PREFIX_KEY, "widgets"); echo "Prefix key is now: ", $m->getOption(Memcached::OPT_PREFIX_KEY), "\n"; ?> ``` The above example will output: ``` bool(true) Prefix key is now: widgets ``` ### See Also * [Memcached::getOption()](memcached.getoption) - Retrieve a Memcached option value * [Memcached::setOptions()](memcached.setoptions) - Set Memcached options * [Memcached Constants](https://www.php.net/manual/en/memcached.constants.php) php SplFileInfo::getPathname SplFileInfo::getPathname ======================== (PHP 5 >= 5.1.2, PHP 7, PHP 8) SplFileInfo::getPathname — Gets the path to the file ### Description ``` public SplFileInfo::getPathname(): string ``` Returns the path to the file. ### Parameters This function has no parameters. ### Return Values The path to the file. ### Examples **Example #1 **SplFileInfo::getPathname()** example** ``` <?php $info = new SplFileInfo('/usr/bin/php'); var_dump($info->getPathname()); ?> ``` The above example will output something similar to: ``` string(12) "/usr/bin/php" ``` ### See Also * [SplFileInfo::getRealPath()](splfileinfo.getrealpath) - Gets absolute path to file php ftp_rmdir ftp\_rmdir ========== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_rmdir — Removes a directory ### Description ``` ftp_rmdir(FTP\Connection $ftp, string $directory): bool ``` Removes the specified `directory` on the FTP server. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `directory` The directory to delete. This must be either an absolute or relative path to an empty directory. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_rmdir()** example** ``` <?php $dir = 'www/'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // try to delete the directory $dir if (ftp_rmdir($ftp, $dir)) {     echo "Successfully deleted $dir\n"; } else {     echo "There was a problem while deleting $dir\n"; } ftp_close($ftp); ?> ``` ### See Also * [ftp\_mkdir()](function.ftp-mkdir) - Creates a directory php Event::timer Event::timer ============ (PECL event >= 1.2.6-beta) Event::timer — Constructs timer event object ### Description ``` public static Event::timer( EventBase $base , callable $cb , mixed $arg = ?): Event ``` Constructs timer event object. This is a straightforward method to create a timer event. Note, the generic [Event::\_\_construct()](event.construct) method can contruct signal event objects too. ### Parameters `base` The associated event base object. `cb` The signal event callback. See [Event callbacks](https://www.php.net/manual/en/event.callbacks.php) . `arg` Custom data. If specified, it will be passed to the callback when event triggers. ### Return Values Returns Event object on success. Otherwise **`false`**. php proc_terminate proc\_terminate =============== (PHP 5, PHP 7, PHP 8) proc\_terminate — Kills a process opened by proc\_open ### Description ``` proc_terminate(resource $process, int $signal = 15): bool ``` Signals a `process` (created using [proc\_open()](function.proc-open)) that it should terminate. **proc\_terminate()** returns immediately and does not wait for the process to terminate. **proc\_terminate()** allows you terminate the process and continue with other tasks. You may poll the process (to see if it has stopped yet) by using the [proc\_get\_status()](function.proc-get-status) function. ### Parameters `process` The [proc\_open()](function.proc-open) resource that will be closed. `signal` This optional parameter is only useful on POSIX operating systems; you may specify a signal to send to the process using the `kill(2)` system call. The default is `SIGTERM`. ### Return Values Returns the termination status of the process that was run. ### See Also * [proc\_open()](function.proc-open) - Execute a command and open file pointers for input/output * [proc\_close()](function.proc-close) - Close a process opened by proc\_open and return the exit code of that process * [proc\_get\_status()](function.proc-get-status) - Get information about a process opened by proc\_open php IntlRuleBasedBreakIterator::__construct IntlRuleBasedBreakIterator::\_\_construct ========================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) IntlRuleBasedBreakIterator::\_\_construct — Create iterator from ruleset ### Description public **IntlRuleBasedBreakIterator::\_\_construct**(string `$rules`, bool `$compiled` = **`false`**) **Warning**This function is currently not documented; only its argument list is available. ### Parameters `rules` `compiled` ### Return Values php Yaf_View_Interface::getScriptPath Yaf\_View\_Interface::getScriptPath =================================== (Yaf >=1.0.0) Yaf\_View\_Interface::getScriptPath — The getScriptPath purpose ### Description ``` abstract public Yaf_View_Interface::getScriptPath(): void ``` **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values php ReflectionFunctionAbstract::isGenerator ReflectionFunctionAbstract::isGenerator ======================================= (PHP 5 >= 5.5.0, PHP 7, PHP 8) ReflectionFunctionAbstract::isGenerator — Returns whether this function is a generator ### Description ``` public ReflectionFunctionAbstract::isGenerator(): bool ``` ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the function is generator, **`false`** if it is not or **`null`** on failure. php number_format number\_format ============== (PHP 4, PHP 5, PHP 7, PHP 8) number\_format — Format a number with grouped thousands ### Description ``` number_format( float $num, int $decimals = 0, ?string $decimal_separator = ".", ?string $thousands_separator = "," ): string ``` Formats a number with grouped thousands and optionally decimal digits. ### Parameters `num` The number being formatted. `decimals` Sets the number of decimal digits. If `0`, the `decimal_separator` is omitted from the return value. `decimal_separator` Sets the separator for the decimal point. `thousands_separator` Sets the thousands separator. ### Return Values A formatted version of `num`. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | Prior to this version, **number\_format()** accepted one, two, or four parameters (but not three). | | 7.2.0 | **number\_format()** was changed to not being able to return `-0`, previously `-0` could be returned for cases like where `num` would be `-0.01`. | ### Examples **Example #1 **number\_format()** Example** For instance, French notation usually use two decimals, comma (',') as decimal separator, and space (' ') as thousand separator. The following example demonstrates various ways to format a number: ``` <?php $number = 1234.56; // english notation (default) $english_format_number = number_format($number); // 1,235 // French notation $nombre_format_francais = number_format($number, 2, ',', ' '); // 1 234,56 $number = 1234.5678; // english notation without thousands separator $english_format_number = number_format($number, 2, '.', ''); // 1234.57 ?> ``` ### See Also * [money\_format()](function.money-format) - Formats a number as a currency string * [sprintf()](function.sprintf) - Return a formatted string * [printf()](function.printf) - Output a formatted string * [sscanf()](function.sscanf) - Parses input from a string according to a format
programming_docs
php SolrQuery::removeSortField SolrQuery::removeSortField ========================== (PECL solr >= 0.9.2) SolrQuery::removeSortField — Removes one of the sort fields ### Description ``` public SolrQuery::removeSortField(string $field): SolrQuery ``` Removes one of the sort fields ### Parameters `field` The name of the field ### Return Values Returns the current SolrQuery object, if the return value is used. php inotify_read inotify\_read ============= (PECL inotify >= 0.1.2) inotify\_read — Read events from an inotify instance ### Description ``` inotify_read(resource $inotify_instance): array ``` Read inotify events from an inotify instance. ### Parameters `inotify_instance` Resource returned by [inotify\_init()](function.inotify-init) ### Return Values An array of inotify events or **`false`** if no events was pending and `inotify_instance` is non-blocking. Each event is an array with the following keys: * wd is a watch descriptor returned by [inotify\_add\_watch()](function.inotify-add-watch) * mask is a bit mask of [events](https://www.php.net/manual/en/inotify.constants.php) * cookie is a unique id to connect related events (e.g. **`IN_MOVE_FROM`** and **`IN_MOVE_TO`**) * name is the name of a file (e.g. if a file was modified in a watched directory) ### See Also * [inotify\_init()](function.inotify-init) - Initialize an inotify instance * [stream\_select()](function.stream-select) - Runs the equivalent of the select() system call on the given arrays of streams with a timeout specified by seconds and microseconds * [stream\_set\_blocking()](function.stream-set-blocking) - Set blocking/non-blocking mode on a stream * [inotify\_queue\_len()](function.inotify-queue-len) - Return a number upper than zero if there are pending events php Yaf_Request_Abstract::isDispatched Yaf\_Request\_Abstract::isDispatched ==================================== (Yaf >=1.0.0) Yaf\_Request\_Abstract::isDispatched — Determin if the request is dispatched ### Description ``` public Yaf_Request_Abstract::isDispatched(): bool ``` ### Parameters This function has no parameters. ### Return Values boolean ### See Also * [Yaf\_Dispatcher::dispatch()](yaf-dispatcher.dispatch) - Dispatch a request php odbc_field_type odbc\_field\_type ================= (PHP 4, PHP 5, PHP 7, PHP 8) odbc\_field\_type — Datatype of a field ### Description ``` odbc_field_type(resource $statement, int $field): string|false ``` Gets the SQL type of the field referenced by number in the given result identifier. ### Parameters `statement` The result identifier. `field` The field number. Field numbering starts at 1. ### Return Values Returns the field type as a string, or **`false`** on error. php SolrResponse::getRawRequestHeaders SolrResponse::getRawRequestHeaders ================================== (PECL solr >= 0.9.2) SolrResponse::getRawRequestHeaders — Returns the raw request headers sent to the Solr server ### Description ``` public SolrResponse::getRawRequestHeaders(): string ``` Returns the raw request headers sent to the Solr server. ### Parameters This function has no parameters. ### Return Values Returns the raw request headers sent to the Solr server php QuickHashStringIntHash::add QuickHashStringIntHash::add =========================== (No version information available, might only be in Git) QuickHashStringIntHash::add — This method adds a new entry to the hash ### Description ``` public QuickHashStringIntHash::add(string $key, int $value): bool ``` This method adds a new entry to the hash, and returns whether the entry was added. Entries are by default always added unless **`QuickHashStringIntHash::CHECK_FOR_DUPES`** has been passed when the hash was created. ### Parameters `key` The key of the entry to add. `value` The value of the entry to add. ### Return Values **`true`** when the entry was added, and **`false`** if the entry was not added. ### Examples **Example #1 **QuickHashStringIntHash::add()** example** ``` <?php echo "without dupe checking\n"; $hash = new QuickHashStringIntHash( 1024 ); var_dump( $hash ); var_dump( $hash->exists( "four" ) ); var_dump( $hash->get( "four" ) ); var_dump( $hash->add( "four", 22 ) ); var_dump( $hash->exists( "four" ) ); var_dump( $hash->get( "four" ) ); var_dump( $hash->add( "four", 12 ) ); echo "\nwith dupe checking\n"; $hash = new QuickHashStringIntHash( 1024, QuickHashStringIntHash::CHECK_FOR_DUPES ); var_dump( $hash ); var_dump( $hash->exists( "four" ) ); var_dump( $hash->get( "four" ) ); var_dump( $hash->add( "four", 78 ) ); var_dump( $hash->exists( "four" ) ); var_dump( $hash->get( "four" ) ); var_dump( $hash->add( "four", 9 ) ); ?> ``` The above example will output something similar to: ``` without dupe checking object(QuickHashStringIntHash)#1 (0) { } bool(false) bool(false) bool(true) bool(true) int(22) bool(true) with dupe checking object(QuickHashStringIntHash)#2 (0) { } bool(false) bool(false) bool(true) bool(true) int(78) bool(false) ``` php radius_acct_open radius\_acct\_open ================== (PECL radius >= 1.1.0) radius\_acct\_open — Creates a Radius handle for accounting ### Description ``` radius_acct_open(): resource ``` ### Parameters This function has no parameters. ### Return Values Returns a handle on success, **`false`** on error. This function only fails if insufficient memory is available. ### Examples **Example #1 **radius\_acct\_open()** example** ``` <?php $res = radius_acct_open ()     or die ("Could not create handle"); print("Handle successfully created"); ?> ``` php GearmanClient::addTaskLowBackground GearmanClient::addTaskLowBackground =================================== (PECL gearman >= 0.5.0) GearmanClient::addTaskLowBackground — Add a low priority background task to be run in parallel ### Description ``` public GearmanClient::addTaskLowBackground( string $function_name, string $workload, mixed &$context = ?, string $unique = ? ): GearmanTask ``` Adds a low priority background task to be run in parallel with other tasks. Call this method for all the tasks to be run in parallel, then call [GearmanClient::runTasks()](gearmanclient.runtasks) to perform the work. Tasks with a low priority will be selected from the queue after those of normal or high priority. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `context` Application context to associate with a task `unique` A unique ID used to identify a particular task ### Return Values A [GearmanTask](class.gearmantask) object or **`false`** if the task could not be added. ### See Also * [GearmanClient::addTask()](gearmanclient.addtask) - Add a task to be run in parallel * [GearmanClient::addTaskHigh()](gearmanclient.addtaskhigh) - Add a high priority task to run in parallel * [GearmanClient::addTaskLow()](gearmanclient.addtasklow) - Add a low priority task to run in parallel * [GearmanClient::addTaskBackground()](gearmanclient.addtaskbackground) - Add a background task to be run in parallel * [GearmanClient::addTaskHighBackground()](gearmanclient.addtaskhighbackground) - Add a high priority background task to be run in parallel * [GearmanClient::runTasks()](gearmanclient.runtasks) - Run a list of tasks in parallel php fbird_service_detach fbird\_service\_detach ====================== (PHP 5, PHP 7 < 7.4.0) fbird\_service\_detach — Alias of [ibase\_service\_detach()](function.ibase-service-detach) ### Description This function is an alias of: [ibase\_service\_detach()](function.ibase-service-detach). php ImagickDraw::arc ImagickDraw::arc ================ (PECL imagick 2, PECL imagick 3) ImagickDraw::arc — Draws an arc ### Description ``` public ImagickDraw::arc( float $sx, float $sy, float $ex, float $ey, float $sd, float $ed ): bool ``` **Warning**This function is currently not documented; only its argument list is available. Draws an arc falling within a specified bounding rectangle on the image. ### Parameters `sx` Starting x ordinate of bounding rectangle `sy` starting y ordinate of bounding rectangle `ex` ending x ordinate of bounding rectangle `ey` ending y ordinate of bounding rectangle `sd` starting degrees of rotation `ed` ending degrees of rotation ### Return Values No value is returned. ### Examples **Example #1 **ImagickDraw::arc()** example** ``` <?php function arc($strokeColor, $fillColor, $backgroundColor, $startX, $startY, $endX, $endY, $startAngle, $endAngle) {     //Create a ImagickDraw object to draw into.     $draw = new \ImagickDraw();     $draw->setStrokeWidth(1);     $draw->setStrokeColor($strokeColor);     $draw->setFillColor($fillColor);     $draw->setStrokeWidth(2);     $draw->arc($startX, $startY, $endX, $endY, $startAngle, $endAngle);     //Create an image object which the draw commands can be rendered into     $image = new \Imagick();     $image->newImage(IMAGE_WIDTH, IMAGE_HEIGHT, $backgroundColor);     $image->setImageFormat("png");     //Render the draw commands in the ImagickDraw object      //into the image.     $image->drawImage($draw);     //Send the image to the browser     header("Content-Type: image/png");     echo $image->getImageBlob(); } ?> ``` php openssl_x509_fingerprint openssl\_x509\_fingerprint ========================== (PHP 5 >= 5.6.0, PHP 7, PHP 8) openssl\_x509\_fingerprint — Calculates the fingerprint, or digest, of a given X.509 certificate ### Description ``` openssl_x509_fingerprint(OpenSSLCertificate|string $certificate, string $digest_algo = "sha1", bool $binary = false): string|false ``` **openssl\_x509\_fingerprint()** returns the digest of `certificate` as a string. ### Parameters `x509` See [Key/Certificate parameters](https://www.php.net/manual/en/openssl.certparams.php) for a list of valid values. `digest_algo` The digest method or hash algorithm to use, e.g. "sha256", one of [openssl\_get\_md\_methods()](function.openssl-get-md-methods). `binary` When set to **`true`**, outputs raw binary data. **`false`** outputs lowercase hexits. ### Return Values Returns a string containing the calculated certificate fingerprint as lowercase hexits unless `binary` is set to **`true`** in which case the raw binary representation of the message digest is returned. Returns **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `certificate` accepts an [OpenSSLCertificate](class.opensslcertificate) instance now; previously, a [resource](language.types.resource) of type `OpenSSL X.509` was accepted. | php apcu_entry apcu\_entry =========== (PECL apcu >= 5.1.0) apcu\_entry — Atomically fetch or generate a cache entry ### Description ``` apcu_entry(string $key, callable $generator, int $ttl = 0): mixed ``` Atomically attempts to find `key` in the cache, if it cannot be found `generator` is called, passing `key` as the only argument. The return value of the call is then cached with the optionally specified `ttl`, and returned. > **Note**: When control enters **apcu\_entry()** the lock for the cache is acquired exclusively, it is released when control leaves **apcu\_entry()**: In effect, this turns the body of `generator` into a critical section, disallowing two processes from executing the same code paths concurrently. In addition, it prohibits the concurrent execution of any other APCu functions, since they will acquire the same lock. > > **Warning** The only APCu function that can be called safely by `generator` is **apcu\_entry()**. ### Parameters `key` Identity of cache entry `generator` A callable that accepts `key` as the only argument and returns the value to cache. `ttl` Time To Live; store `var` in the cache for `ttl` seconds. After the `ttl` has passed, the stored variable will be expunged from the cache (on the next request). If no `ttl` is supplied (or if the `ttl` is `0`), the value will persist until it is removed from the cache manually, or otherwise fails to exist in the cache (clear, restart, etc.). ### Return Values Returns the cached value ### Examples **Example #1 An **apcu\_entry()** example** ``` <?php $config = apcu_entry("config", function($key) {  return [    "fruit" => apcu_entry("config.fruit", function($key){      return [        "apples",        "pears"      ];    }),     "people" => apcu_entry("config.people", function($key){      return [       "bob",       "joe",       "niki"      ];    })  ]; }); var_dump($config); ?> ``` The above example will output: ``` array(2) { ["fruit"]=> array(2) { [0]=> string(6) "apples" [1]=> string(5) "pears" } ["people"]=> array(3) { [0]=> string(3) "bob" [1]=> string(3) "joe" [2]=> string(4) "niki" } } ``` ### See Also * [apcu\_store()](function.apcu-store) - Cache a variable in the data store * [apcu\_fetch()](function.apcu-fetch) - Fetch a stored variable from the cache * [apcu\_delete()](function.apcu-delete) - Removes a stored variable from the cache php Floating point precision Floating point numbers ---------------------- Floating point numbers (also known as "floats", "doubles", or "real numbers") can be specified using any of the following syntaxes: ``` <?php $a = 1.234;  $b = 1.2e3;  $c = 7E-10; $d = 1_234.567; // as of PHP 7.4.0 ?> ``` Formally as of PHP 7.4.0 (previously, underscores have not been allowed): ``` LNUM [0-9]+(_[0-9]+)* DNUM ([0-9]*(_[0-9]+)*[\.]{LNUM}) | ({LNUM}[\.][0-9]*(_[0-9]+)*) EXPONENT_DNUM (({LNUM} | {DNUM}) [eE][+-]? {LNUM}) ``` The size of a float is platform-dependent, although a maximum of approximately 1.8e308 with a precision of roughly 14 decimal digits is a common value (the 64 bit IEEE format). **Warning** Floating point precision ======================== Floating point numbers have limited precision. Although it depends on the system, PHP typically uses the IEEE 754 double precision format, which will give a maximum relative error due to rounding in the order of 1.11e-16. Non elementary arithmetic operations may give larger errors, and, of course, error propagation must be considered when several operations are compounded. Additionally, rational numbers that are exactly representable as floating point numbers in base 10, like `0.1` or `0.7`, do not have an exact representation as floating point numbers in base 2, which is used internally, no matter the size of the mantissa. Hence, they cannot be converted into their internal binary counterparts without a small loss of precision. This can lead to confusing results: for example, `floor((0.1+0.7)*10)` will usually return `7` instead of the expected `8`, since the internal representation will be something like `7.9999999999999991118...`. So never trust floating number results to the last digit, and do not compare floating point numbers directly for equality. If higher precision is necessary, the [arbitrary precision math functions](https://www.php.net/manual/en/ref.bc.php) and [gmp](https://www.php.net/manual/en/ref.gmp.php) functions are available. For a "simple" explanation, see the [» floating point guide](http://floating-point-gui.de/) that's also titled "Why don’t my numbers add up?" ### Converting to float #### From strings If the string is [numeric](language.types.numeric-strings) or leading numeric then it will resolve to the corresponding float value, otherwise it is converted to zero (`0`). #### From other types For values of other types, the conversion is performed by converting the value to int first and then to float. See [Converting to integer](language.types.integer#language.types.integer.casting) for more information. > > **Note**: > > > As certain types have undefined behavior when converting to int, this is also the case when converting to float. > > ### Comparing floats As noted in the warning above, testing floating point values for equality is problematic, due to the way that they are represented internally. However, there are ways to make comparisons of floating point values that work around these limitations. To test floating point values for equality, an upper bound on the relative error due to rounding is used. This value is known as the machine epsilon, or unit roundoff, and is the smallest acceptable difference in calculations. $a and $b are equal to 5 digits of precision. ``` <?php $a = 1.23456789; $b = 1.23456780; $epsilon = 0.00001; if(abs($a-$b) < $epsilon) {     echo "true"; } ?> ``` ### NaN Some numeric operations can result in a value represented by the constant **`NAN`**. This result represents an undefined or unrepresentable value in floating-point calculations. Any loose or strict comparisons of this value against any other value, including itself, but except **`true`**, will have a result of **`false`**. Because **`NAN`** represents any number of different values, **`NAN`** should not be compared to other values, including itself, and instead should be checked for using [is\_nan()](function.is-nan). php IteratorIterator::key IteratorIterator::key ===================== (PHP 5 >= 5.1.0, PHP 7, PHP 8) IteratorIterator::key — Get the key of the current element ### Description ``` public IteratorIterator::key(): mixed ``` Get the key of the current element. ### Parameters This function has no parameters. ### Return Values The key of the current element. ### See Also * [IteratorIterator::current()](iteratoriterator.current) - Get the current value php snmp_get_valueretrieval snmp\_get\_valueretrieval ========================= (PHP 4 >= 4.3.3, PHP 5, PHP 7, PHP 8) snmp\_get\_valueretrieval — Return the method how the SNMP values will be returned ### Description ``` snmp_get_valueretrieval(): int ``` ### Parameters This function has no parameters. ### Return Values OR-ed combitantion of constants ( **`SNMP_VALUE_LIBRARY`** or **`SNMP_VALUE_PLAIN`** ) with possible SNMP\_VALUE\_OBJECT set. ### Examples **Example #1 Using **snmp\_get\_valueretrieval()**** ``` <?php  $ret = snmpget('localhost', 'public', 'IF-MIB::ifName.1');  if (snmp_get_valueretrieval() & SNMP_VALUE_OBJECT) {    echo $ret->value;  } else {    echo $ret;  } ?> ``` ### See Also * [snmp\_set\_valueretrieval()](function.snmp-set-valueretrieval) - Specify the method how the SNMP values will be returned * [Predefined Constants](https://www.php.net/manual/en/snmp.constants.php) php PharFileInfo::chmod PharFileInfo::chmod =================== (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL phar >= 1.0.0) PharFileInfo::chmod — Sets file-specific permission bits ### Description ``` public PharFileInfo::chmod(int $perms): void ``` **PharFileInfo::chmod()** allows setting of the executable file permissions bit, as well as read-only bits. Writeable bits are ignored, and set at runtime based on the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable. As with all functionality that modifies the contents of a phar, the [phar.readonly](https://www.php.net/manual/en/phar.configuration.php#ini.phar.readonly) INI variable must be off in order to succeed if the file is within a [Phar](class.phar) archive. Files within [PharData](class.phardata) archives do not have this restriction. ### Parameters `perms` permissions (see [chmod()](function.chmod)) ### Return Values No value is returned. ### Examples **Example #1 A **PharFileInfo::chmod()** example** ``` <?php // make sure it doesn't exist @unlink('brandnewphar.phar'); try {     $p = new Phar('brandnewphar.phar', 0, 'brandnewphar.phar');     $p['file.sh'] = '#!/usr/local/lib/php     <?php echo "hi"; ?>';     // set executable bit     $p['file.sh']->chmod(0555);     var_dump($p['file.sh']->isExecutable()); } catch (Exception $e) {     echo 'Could not create/modify phar: ', $e; } ?> ``` The above example will output: ``` bool(true) ```
programming_docs
php Ds\Map::capacity Ds\Map::capacity ================ (PECL ds >= 1.0.0) Ds\Map::capacity — Returns the current capacity ### Description ``` public Ds\Map::capacity(): int ``` Returns the current capacity. ### Parameters This function has no parameters. ### Return Values The current capacity. ### Examples **Example #1 **Ds\Map::capacity()** example** ``` <?php $map = new \Ds\Map(); var_dump($map->capacity()); ?> ``` The above example will output something similar to: ``` int(16) ``` php ReflectionParameter::getType ReflectionParameter::getType ============================ (PHP 7, PHP 8) ReflectionParameter::getType — Gets a parameter's type ### Description ``` public ReflectionParameter::getType(): ?ReflectionType ``` Gets the associated type of a parameter. ### Parameters This function has no parameters. ### Return Values Returns a [ReflectionType](class.reflectiontype) object if a parameter type is specified, **`null`** otherwise. ### Examples **Example #1 **ReflectionParameter::getType()** Usage as of PHP 7.1.0** As of PHP 7.1.0, [ReflectionType::\_\_toString()](reflectiontype.tostring) is deprecated, and **ReflectionParameter::getType()** *may* return an instance of [ReflectionNamedType](class.reflectionnamedtype). To get the name of the parameter type, **ReflectionNamedType()** is available in this case. ``` <?php function someFunction(int $param, $param2) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParams = $reflectionFunc->getParameters(); $reflectionType1 = $reflectionParams[0]->getType(); $reflectionType2 = $reflectionParams[1]->getType(); assert($reflectionType1 instanceof ReflectionNamedType); echo $reflectionType1->getName(), PHP_EOL; var_dump($reflectionType2); ?> ``` The above example will output: ``` int NULL ``` **Example #2 **ReflectionParameter::getType()** Usage before PHP 7.1.0** ``` <?php function someFunction(int $param, $param2) {} $reflectionFunc = new ReflectionFunction('someFunction'); $reflectionParams = $reflectionFunc->getParameters(); $reflectionType1 = $reflectionParams[0]->getType(); $reflectionType2 = $reflectionParams[1]->getType(); echo $reflectionType1, PHP_EOL; var_dump($reflectionType2); ?> ``` Output of the above example in PHP 7.0: ``` int NULL ``` **Example #3 **ReflectionParameter::getType()** Usage in PHP 8.0.0 and later** As of PHP 8.0.0, this method may return a [ReflectionNamedType](class.reflectionnamedtype) instance or a [ReflectionUnionType](class.reflectionuniontype) instance. The latter is a collection of the former. To analyze a type, it is often convenient to normalize it to an array of [ReflectionNamedType](class.reflectionnamedtype) objects. The following function will return an array of `0` or more [ReflectionNamedType](class.reflectionnamedtype) instances. ``` <?php function getAllTypes(ReflectionParameter $reflectionParameter): array {     $reflectionType = $reflectionParameter->getType();     if (!$reflectionType) return [];     return $reflectionType instanceof ReflectionUnionType         ? $reflectionType->getTypes()         : [$reflectionType]; } ?> ``` ### See Also * [ReflectionParameter::hasType()](reflectionparameter.hastype) - Checks if parameter has a type * [ReflectionType::\_\_toString()](reflectiontype.tostring) - To string php OAuth::enableRedirects OAuth::enableRedirects ====================== (PECL OAuth >= 0.99.9) OAuth::enableRedirects — Turn on redirects ### Description ``` public OAuth::enableRedirects(): bool ``` Follow and sign redirects automatically, which is enabled by default. **Warning**This function is currently not documented; only its argument list is available. ### Parameters This function has no parameters. ### Return Values **`true`** ### See Also * [OAuth::disableRedirects()](oauth.disableredirects) - Turn off redirects php GearmanJob::fail GearmanJob::fail ================ (PECL gearman <= 0.5.0) GearmanJob::fail — Send fail status (deprecated) ### Description ``` public GearmanJob::fail(): bool ``` Sends failure status for this job, indicating that the job failed in a known way (as opposed to failing due to a thrown exception). > > **Note**: > > > This method has been replaced by [GearmanJob::sendFail()](gearmanjob.sendfail) in the 0.6.0 release of the Gearman extension. > > ### Parameters This function has no parameters. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::sendException()](gearmanjob.sendexception) - Send exception for running job (exception) * [GearmanJob::setReturn()](gearmanjob.setreturn) - Set a return value * [GearmanJob::sendStatus()](gearmanjob.sendstatus) - Send status * [GearmanJob::sendWarning()](gearmanjob.sendwarning) - Send a warning php Gmagick::hasnextimage Gmagick::hasnextimage ===================== (PECL gmagick >= Unknown) Gmagick::hasnextimage — Checks if the object has more images ### Description ``` public Gmagick::hasnextimage(): mixed ``` Returns **`true`** if the object has more images when traversing the list in the forward direction. ### Parameters This function has no parameters. ### Return Values Returns **`true`** if the object has more images when traversing the list in the forward direction, returns **`false`** if there are none. ### Errors/Exceptions Throws an **GmagickException** on error. php SolrQuery::setRows SolrQuery::setRows ================== (PECL solr >= 0.9.2) SolrQuery::setRows — Specifies the maximum number of rows to return in the result ### Description ``` public SolrQuery::setRows(int $rows): SolrQuery ``` Specifies the maximum number of rows to return in the result ### Parameters `rows` The maximum number of rows to return ### Return Values Returns the current SolrQuery object. php SolrResponse::getHttpStatusMessage SolrResponse::getHttpStatusMessage ================================== (PECL solr >= 0.9.2) SolrResponse::getHttpStatusMessage — Returns more details on the HTTP status ### Description ``` public SolrResponse::getHttpStatusMessage(): string ``` Returns more details on the HTTP status. ### Parameters This function has no parameters. ### Return Values Returns more details on the HTTP status php ftp_delete ftp\_delete =========== (PHP 4, PHP 5, PHP 7, PHP 8) ftp\_delete — Deletes a file on the FTP server ### Description ``` ftp_delete(FTP\Connection $ftp, string $filename): bool ``` **ftp\_delete()** deletes the file specified by `filename` from the FTP server. ### Parameters `ftp` An [FTP\Connection](class.ftp-connection) instance. `filename` The file to delete. ### Return Values Returns **`true`** on success or **`false`** on failure. ### Changelog | Version | Description | | --- | --- | | 8.1.0 | The `ftp` parameter expects an [FTP\Connection](class.ftp-connection) instance now; previously, a [resource](language.types.resource) was expected. | ### Examples **Example #1 **ftp\_delete()** example** ``` <?php $file = 'public_html/old.txt'; // set up basic connection $ftp = ftp_connect($ftp_server); // login with username and password $login_result = ftp_login($ftp, $ftp_user_name, $ftp_user_pass); // try to delete $file if (ftp_delete($ftp, $file)) {  echo "$file deleted successful\n"; } else {  echo "could not delete $file\n"; } // close the connection ftp_close($ftp); ?> ``` php The DateInterval class The DateInterval class ====================== Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8) Represents a date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that [DateTimeImmutable](class.datetimeimmutable)'s and [DateTime](class.datetime)'s constructors support. More specifically, the information in an object of the **DateInterval** class is an instruction to get from one date/time to another date/time. This process is not always reversible. A common way to create a **DateInterval** object is by calculating the difference between two date/time objects through [DateTimeInterface::diff()](datetime.diff). Since there is no well defined way to compare date intervals, **DateInterval** instances are [incomparable](language.operators.comparison#language.operators.comparison.incomparable). Class synopsis -------------- class **DateInterval** { /\* Properties \*/ public int [$y](class.dateinterval#dateinterval.props.y); public int [$m](class.dateinterval#dateinterval.props.m); public int [$d](class.dateinterval#dateinterval.props.d); public int [$h](class.dateinterval#dateinterval.props.h); public int [$i](class.dateinterval#dateinterval.props.i); public int [$s](class.dateinterval#dateinterval.props.s); public float [$f](class.dateinterval#dateinterval.props.f); public int [$invert](class.dateinterval#dateinterval.props.invert); public [mixed](language.types.declarations#language.types.declarations.mixed) [$days](class.dateinterval#dateinterval.props.days); public bool [$from\_string](class.dateinterval#dateinterval.props.from-string); public string [$date\_string](class.dateinterval#dateinterval.props.date-string); /\* Methods \*/ public [\_\_construct](dateinterval.construct)(string `$duration`) ``` public static createFromDateString(string $datetime): DateInterval|false ``` ``` public format(string $format): string ``` } Properties ---------- **Warning** The available properties listed below depend on PHP version, and should be considered as *readonly*. y Number of years. m Number of months. d Number of days. h Number of hours. i Number of minutes. s Number of seconds. f Number of microseconds, as a fraction of a second. invert Is `1` if the interval represents a negative time period and `0` otherwise. See [DateInterval::format()](dateinterval.format). days If the DateInterval object was created by [DateTimeImmutable::diff()](datetime.diff) or [DateTime::diff()](datetime.diff), then this is the total number of full days between the start and end dates. Otherwise, days will be **`false`**. from\_string If the DateInterval object was created by [DateInterval::createFromDateString()](dateinterval.createfromdatestring), then this property's value will be **`true`**, and the date\_string property will be populated. Otherwise, the value will be **`false`**, and the y to f, invert, and days properties will be populated. date\_string The string used as argument to [DateInterval::createFromDateString()](dateinterval.createfromdatestring). Changelog --------- | Version | Description | | --- | --- | | 8.2.0 | The from\_string and date\_string properties were added for **DateInterval** instances that were created using the [DateInterval::createFromDateString()](dateinterval.createfromdatestring) method. | | 8.2.0 | Only the `y` to `f`, `invert`, and `days` will be visible. | | 7.4.0 | **DateInterval** instances are incomparable now; previously, all **DateInterval** instances were considered equal. | | 7.1.0 | The f property was added. | Table of Contents ----------------- * [DateInterval::\_\_construct](dateinterval.construct) — Creates a new DateInterval object * [DateInterval::createFromDateString](dateinterval.createfromdatestring) — Sets up a DateInterval from the relative parts of the string * [DateInterval::format](dateinterval.format) — Formats the interval php EvLoop::verify EvLoop::verify ============== (PECL ev >= 0.2.0) EvLoop::verify — Performs internal consistency checks(for debugging) ### Description ``` public EvLoop::verify(): void ``` Performs internal consistency checks(for debugging *libev* ) and abort the program if any data structures were found to be corrupted. ### Parameters This function has no parameters. ### Return Values No value is returned. ### See Also * [Ev::verify()](ev.verify) - Performs internal consistency checks(for debugging) php stream_set_read_buffer stream\_set\_read\_buffer ========================= (PHP 5 >= 5.3.3, PHP 7, PHP 8) stream\_set\_read\_buffer — Set read file buffering on the given stream ### Description ``` stream_set_read_buffer(resource $stream, int $size): int ``` Sets the read buffer. It's the equivalent of [stream\_set\_write\_buffer()](function.stream-set-write-buffer), but for read operations. ### Parameters `stream` The file pointer. `size` The number of bytes to buffer. If `size` is 0 then read operations are unbuffered. This ensures that all reads with [fread()](function.fread) are completed before other processes are allowed to read from that input stream. ### Return Values Returns 0 on success, or another value if the request cannot be honored. ### See Also * [stream\_set\_write\_buffer()](function.stream-set-write-buffer) - Sets write file buffering on the given stream php The Yaf_Exception_RouterFailed class The Yaf\_Exception\_RouterFailed class ====================================== Introduction ------------ (Yaf >=1.0.0) Class synopsis -------------- class **Yaf\_Exception\_RouterFailed** extends [Yaf\_Exception](class.yaf-exception) { /\* Properties \*/ /\* Methods \*/ /\* Inherited methods \*/ ``` public Yaf_Exception::getPrevious(): void ``` } php None Incrementing/Decrementing Operators ----------------------------------- PHP supports C-style pre- and post-increment and decrement operators. > **Note**: The increment/decrement operators only affect numbers and strings. Arrays, objects, booleans and resources are not affected. Decrementing **`null`** values has no effect too, but incrementing them results in `1`. > > **Increment/decrement Operators**| Example | Name | Effect | | --- | --- | --- | | ++$a | Pre-increment | Increments $a by one, then returns $a. | | $a++ | Post-increment | Returns $a, then increments $a by one. | | --$a | Pre-decrement | Decrements $a by one, then returns $a. | | $a-- | Post-decrement | Returns $a, then decrements $a by one. | Here's a simple example script: ``` <?php echo "<h3>Postincrement</h3>"; $a = 5; echo "Should be 5: " . $a++ . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Preincrement</h3>"; $a = 5; echo "Should be 6: " . ++$a . "<br />\n"; echo "Should be 6: " . $a . "<br />\n"; echo "<h3>Postdecrement</h3>"; $a = 5; echo "Should be 5: " . $a-- . "<br />\n"; echo "Should be 4: " . $a . "<br />\n"; echo "<h3>Predecrement</h3>"; $a = 5; echo "Should be 4: " . --$a . "<br />\n"; echo "Should be 4: " . $a . "<br />\n"; ?> ``` PHP follows Perl's convention when dealing with arithmetic operations on character variables and not C's. For example, in PHP and Perl `$a = 'Z'; $a++;` turns `$a` into `'AA'`, while in C `a = 'Z'; a++;` turns `a` into `'['` (ASCII value of `'Z'` is 90, ASCII value of `'['` is 91). Note that character variables can be incremented but not decremented and even so only plain ASCII letters and digits (a-z, A-Z and 0-9) are supported. Incrementing/decrementing other character variables has no effect, the original string is unchanged. **Example #1 Arithmetic Operations on Character Variables** ``` <?php echo '== Alphabetic strings ==' . PHP_EOL; $s = 'W'; for ($n=0; $n<6; $n++) {     echo ++$s . PHP_EOL; } // Alphanumeric strings behave differently echo '== Alphanumeric strings ==' . PHP_EOL; $d = 'A8'; for ($n=0; $n<6; $n++) {     echo ++$d . PHP_EOL; } $d = 'A08'; for ($n=0; $n<6; $n++) {     echo ++$d . PHP_EOL; } ?> ``` The above example will output: ``` == Alphabetic strings == X Y Z AA AB AC == Alphanumeric strings == A9 B0 B1 B2 B3 B4 A09 A10 A11 A12 A13 A14 ``` Incrementing or decrementing booleans has no effect. php abs abs === (PHP 4, PHP 5, PHP 7, PHP 8) abs — Absolute value ### Description ``` abs(int|float $num): int|float ``` Returns the absolute value of `num`. ### Parameters `num` The numeric value to process ### Return Values The absolute value of `num`. If the argument `num` is of type float, the return type is also float, otherwise it is int (as float usually has a bigger value range than int). ### Changelog | Version | Description | | --- | --- | | 8.0.0 | `num` no longer accepts internal objects which support numeric conversion. | ### Examples **Example #1 **abs()** example** ``` <?php var_dump(abs(-4.2)); var_dump(abs(5)); var_dump(abs(-5)); ?> ``` The above example will output: ``` float(4.2) int(5) int(5) ``` ### See Also * [gmp\_abs()](function.gmp-abs) - Absolute value * [gmp\_sign()](function.gmp-sign) - Sign of number php hash_equals hash\_equals ============ (PHP 5 >= 5.6.0, PHP 7, PHP 8) hash\_equals — Timing attack safe string comparison ### Description ``` hash_equals(string $known_string, string $user_string): bool ``` Compares two strings using the same time whether they're equal or not. This function should be used to mitigate timing attacks; for instance, when testing [crypt()](function.crypt) password hashes. ### Parameters `known_string` The string of known length to compare against `user_string` The user-supplied string ### Return Values Returns **`true`** when the two strings are equal, **`false`** otherwise. ### Examples **Example #1 **hash\_equals()** example** ``` <?php $expected  = crypt('12345', '$2a$07$usesomesillystringforsalt$'); $correct   = crypt('12345', '$2a$07$usesomesillystringforsalt$'); $incorrect = crypt('apple', '$2a$07$usesomesillystringforsalt$'); var_dump(hash_equals($expected, $correct)); var_dump(hash_equals($expected, $incorrect)); ?> ``` The above example will output: ``` bool(true) bool(false) ``` ### Notes > > **Note**: > > > Both arguments must be of the same length to be compared successfully. When arguments of differing length are supplied, **`false`** is returned immediately and the length of the known string may be leaked in case of a timing attack. > > > > **Note**: > > > It is important to provide the user-supplied string as the second parameter, rather than the first. > > php phpdbg_break_file phpdbg\_break\_file =================== (PHP 5 >= 5.6.3, PHP 7, PHP 8) phpdbg\_break\_file — Inserts a breakpoint at a line in a file ### Description ``` phpdbg_break_file(string $file, int $line): void ``` Insert a breakpoint at the given `line` in the given `file`. ### Parameters `file` The name of the file. `line` The line number. ### Return Values No value is returned. ### See Also * [phpdbg\_break\_function()](function.phpdbg-break-function) - Inserts a breakpoint at entry to a function * [phpdbg\_break\_method()](function.phpdbg-break-method) - Inserts a breakpoint at entry to a method * [phpdbg\_break\_next()](function.phpdbg-break-next) - Inserts a breakpoint at the next opcode * [phpdbg\_clear()](function.phpdbg-clear) - Clears all breakpoints php Imagick::waveImage Imagick::waveImage ================== (PECL imagick 2, PECL imagick 3) Imagick::waveImage — Applies wave filter to the image ### Description ``` public Imagick::waveImage(float $amplitude, float $length): bool ``` Applies a wave filter to the image. This method is available if Imagick has been compiled against ImageMagick version 6.2.9 or newer. ### Parameters `amplitude` The amplitude of the wave. `length` The length of the wave. ### Return Values Returns **`true`** on success. ### Errors/Exceptions Throws ImagickException on error. ### Examples **Example #1 WaveImage can be quite slow **Imagick::waveImage()**** ``` <?php function waveImage($imagePath, $amplitude, $length) {     $imagick = new \Imagick(realpath($imagePath));     $imagick->waveImage($amplitude, $length);     header("Content-Type: image/jpg");     echo $imagick->getImageBlob(); } ?> ``` ### See Also * [Imagick::solarizeImage()](imagick.solarizeimage) - Applies a solarizing effect to the image * [Imagick::oilpaintImage()](imagick.oilpaintimage) - Simulates an oil painting * [Imagick::embossImage()](imagick.embossimage) - Returns a grayscale image with a three-dimensional effect * [Imagick::addNoiseImage()](imagick.addnoiseimage) - Adds random noise to the image * [Imagick::swirlImage()](imagick.swirlimage) - Swirls the pixels about the center of the image
programming_docs
php mysqli::real_query mysqli::real\_query =================== mysqli\_real\_query =================== (PHP 5, PHP 7, PHP 8) mysqli::real\_query -- mysqli\_real\_query — Execute an SQL query ### Description Object-oriented style ``` public mysqli::real_query(string $query): bool ``` Procedural style ``` mysqli_real_query(mysqli $mysql, string $query): bool ``` Executes a single query against the database whose result can then be retrieved or stored using the [mysqli\_store\_result()](mysqli.store-result) or [mysqli\_use\_result()](mysqli.use-result) functions. In order to determine if a given query should return a result set or not, see [mysqli\_field\_count()](mysqli.field-count). ### Parameters `mysql` Procedural style only: A [mysqli](class.mysqli) object returned by [mysqli\_connect()](function.mysqli-connect) or [mysqli\_init()](mysqli.init) `query` The query string. **Warning** Security warning: SQL injection =============================== If the query contains any variable input then [parameterized prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) should be used instead. Alternatively, the data must be properly formatted and all strings must be escaped using the [mysqli\_real\_escape\_string()](mysqli.real-escape-string) function. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [mysqli\_query()](mysqli.query) - Performs a query on the database * [mysqli\_store\_result()](mysqli.store-result) - Transfers a result set from the last query * [mysqli\_use\_result()](mysqli.use-result) - Initiate a result set retrieval php GearmanClient::doLow GearmanClient::doLow ==================== (PECL gearman >= 0.5.0) GearmanClient::doLow — Run a single low priority task ### Description ``` public GearmanClient::doLow(string $function_name, string $workload, string $unique = ?): string ``` Runs a single low priority task and returns a string representation of the result. It is up to the [GearmanClient](class.gearmanclient) and [GearmanWorker](class.gearmanworker) to agree on the format of the result. Normal and high priority tasks will get precedence over low priority tasks in the job queue. ### Parameters `function_name` A registered function the worker is to execute `workload` Serialized data to be processed `unique` A unique ID used to identify a particular task ### Return Values A string representing the results of running a task. ### See Also * [GearmanClient::doNormal()](gearmanclient.donormal) - Run a single task and return a result * [GearmanClient::doHigh()](gearmanclient.dohigh) - Run a single high priority task * [GearmanClient::doBackground()](gearmanclient.dobackground) - Run a task in the background * [GearmanClient::doHighBackground()](gearmanclient.dohighbackground) - Run a high priority task in the background * [GearmanClient::doLowBackground()](gearmanclient.dolowbackground) - Run a low priority task in the background php GearmanJob::sendData GearmanJob::sendData ==================== (PECL gearman >= 0.6.0) GearmanJob::sendData — Send data for a running job ### Description ``` public GearmanJob::sendData(string $data): bool ``` Sends data to the job server (and any listening clients) for this job. ### Parameters `data` Arbitrary serialized data. ### Return Values Returns **`true`** on success or **`false`** on failure. ### See Also * [GearmanJob::workload()](gearmanjob.workload) - Get workload * [GearmanTask::data()](gearmantask.data) - Get data returned for a task php The EvIo class The EvIo class ============== Introduction ------------ (PECL ev >= 0.2.0) **EvIo** watchers check whether a file descriptor(or socket, or a stream castable to numeric file descriptor) is readable or writable in each iteration of the event loop, or, more precisely, when reading would not block the process and writing would at least be able to write some data. This behaviour is called *level-triggering* because events are kept receiving as long as the condition persists. To stop receiving events just stop the watcher. The number of read and/or write event watchers per `fd` is unlimited. Setting all file descriptors to non-blocking mode is also usually a good idea(but not required). Another thing to watch out for is that it is quite easy to receive false readiness notifications, i.e. the callback might be called with **`Ev::READ`** but a subsequent *read()* will actually block because there is no data. It is very easy to get into this situation. Thus it is best to always use non-blocking I/O: An extra *read()* returning **`EAGAIN`** (or similar) is far preferable to a program hanging until some data arrives. If for some reason it is impossible to run the `fd` in non-blocking mode, then separately re-test whether a file descriptor is really ready. Some people additionally use **`SIGALRM`** and an interval timer, just to be sure thry won't block infinitely. Always consider using non-blocking mode. Class synopsis -------------- class **EvIo** extends [EvWatcher](class.evwatcher) { /\* Properties \*/ public [$fd](class.evio#evio.props.fd); public [$events](class.evio#evio.props.events); /\* Inherited properties \*/ public [$is\_active](class.evwatcher#evwatcher.props.is-active); public [$data](class.evwatcher#evwatcher.props.data); public [$is\_pending](class.evwatcher#evwatcher.props.is-pending); public [$priority](class.evwatcher#evwatcher.props.priority); /\* Methods \*/ public [\_\_construct](evio.construct)( [mixed](language.types.declarations#language.types.declarations.mixed) `$fd` , int `$events` , [callable](language.types.callable) `$callback` , [mixed](language.types.declarations#language.types.declarations.mixed) `$data` = ?, int `$priority` = ? ) ``` final public static createStopped( mixed $fd , int $events , callable $callback , mixed $data = null , int $priority = 0 ): EvIo ``` ``` public set( mixed $fd , int $events ): void ``` /\* Inherited methods \*/ ``` public EvWatcher::clear(): int ``` ``` public EvWatcher::feed( int $revents ): void ``` ``` public EvWatcher::getLoop(): EvLoop ``` ``` public EvWatcher::invoke( int $revents ): void ``` ``` public EvWatcher::keepalive( bool $value = ?): bool ``` ``` public EvWatcher::setCallback( callable $callback ): void ``` ``` public EvWatcher::start(): void ``` ``` public EvWatcher::stop(): void ``` } Properties ---------- fd events Table of Contents ----------------- * [EvIo::\_\_construct](evio.construct) — Constructs EvIo watcher object * [EvIo::createStopped](evio.createstopped) — Create stopped EvIo watcher object * [EvIo::set](evio.set) — Configures the watcher php ctype_alpha ctype\_alpha ============ (PHP 4 >= 4.0.4, PHP 5, PHP 7, PHP 8) ctype\_alpha — Check for alphabetic character(s) ### Description ``` ctype_alpha(mixed $text): bool ``` Checks if all of the characters in the provided string, `text`, are alphabetic. In the standard `C` locale letters are just `[A-Za-z]` and **ctype\_alpha()** is equivalent to `(ctype_upper($text) || ctype_lower($text))` if $text is just a single character, but other languages have letters that are considered neither upper nor lower case. ### Parameters `text` The tested string. > > **Note**: > > > If an int between -128 and 255 inclusive is provided, it is interpreted as the ASCII value of a single character (negative values have 256 added in order to allow characters in the Extended ASCII range). Any other integer is interpreted as a string containing the decimal digits of the integer. > > > **Warning** As of PHP 8.1.0, passing a non-string argument is deprecated. In the future, the argument will be interpreted as a string instead of an ASCII codepoint. Depending on the intended behavior, the argument should either be cast to string or an explicit call to [chr()](function.chr) should be made. ### Return Values Returns **`true`** if every character in `text` is a letter from the current locale, **`false`** otherwise. When called with an empty string the result will always be **`false`**. ### Examples **Example #1 A **ctype\_alpha()** example (using the default locale)** ``` <?php $strings = array('KjgWZC', 'arf12'); foreach ($strings as $testcase) {     if (ctype_alpha($testcase)) {         echo "The string $testcase consists of all letters.\n";     } else {         echo "The string $testcase does not consist of all letters.\n";     } } ?> ``` The above example will output: ``` The string KjgWZC consists of all letters. The string arf12 does not consist of all letters. ``` ### See Also * [ctype\_upper()](function.ctype-upper) - Check for uppercase character(s) * [ctype\_lower()](function.ctype-lower) - Check for lowercase character(s) * [setlocale()](function.setlocale) - Set locale information php DOMDocument::createElementNS DOMDocument::createElementNS ============================ (PHP 5, PHP 7, PHP 8) DOMDocument::createElementNS — Create new element node with an associated namespace ### Description ``` public DOMDocument::createElementNS(?string $namespace, string $qualifiedName, string $value = ""): DOMElement|false ``` This function creates a new element node with an associated namespace. This node will not show up in the document unless it is inserted with (e.g.) [DOMNode::appendChild()](domnode.appendchild). ### Parameters `namespace` The URI of the namespace. `qualifiedName` The qualified name of the element, as `prefix:tagname`. `value` The value of the element. By default, an empty element will be created. You can also set the value later with [DOMElement::$nodeValue](class.domnode#domnode.props.nodevalue). ### Return Values The new [DOMElement](class.domelement) or **`false`** if an error occurred. ### Errors/Exceptions **`DOM_INVALID_CHARACTER_ERR`** Raised if `qualifiedName` contains an invalid character. **`DOM_NAMESPACE_ERR`** Raised if `qualifiedName` is a malformed qualified name. ### Examples **Example #1 Creating a new element and inserting it as root** ``` <?php $dom = new DOMDocument('1.0', 'utf-8'); $element = $dom->createElementNS('http://www.example.com/XFoo', 'xfoo:test', 'This is the root element!'); // We insert the new element as root (child of the document) $dom->appendChild($element); echo $dom->saveXML(); ?> ``` The above example will output: ``` <?xml version="1.0" encoding="utf-8"?> <xfoo:test xmlns:xfoo="http://www.example.com/XFoo">This is the root element!</xfoo:test> ``` **Example #2 A namespace prefix example** ``` <?php $doc  = new DOMDocument('1.0', 'utf-8'); $doc->formatOutput = true; $root = $doc->createElementNS('http://www.w3.org/2005/Atom', 'element'); $doc->appendChild($root); $root->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:g', 'http://base.google.com/ns/1.0'); $item = $doc->createElementNS('http://base.google.com/ns/1.0', 'g:item_type', 'house'); $root->appendChild($item); echo $doc->saveXML(), "\n"; echo $item->namespaceURI, "\n"; // Outputs: http://base.google.com/ns/1.0 echo $item->prefix, "\n";       // Outputs: g echo $item->localName, "\n";    // Outputs: item_type ?> ``` The above example will output: ``` <?xml version="1.0" encoding="utf-8"?> <element xmlns="http://www.w3.org/2005/Atom" xmlns:g="http://base.google.com/ns/1.0"> <g:item_type>house</g:item_type> </element> http://base.google.com/ns/1.0 g item_type ``` ### See Also * [DOMNode::appendChild()](domnode.appendchild) - Adds new child at the end of the children * [DOMDocument::createAttribute()](domdocument.createattribute) - Create new attribute * [DOMDocument::createAttributeNS()](domdocument.createattributens) - Create new attribute node with an associated namespace * [DOMDocument::createCDATASection()](domdocument.createcdatasection) - Create new cdata node * [DOMDocument::createComment()](domdocument.createcomment) - Create new comment node * [DOMDocument::createDocumentFragment()](domdocument.createdocumentfragment) - Create new document fragment * [DOMDocument::createElement()](domdocument.createelement) - Create new element node * [DOMDocument::createEntityReference()](domdocument.createentityreference) - Create new entity reference node * [DOMDocument::createProcessingInstruction()](domdocument.createprocessinginstruction) - Creates new PI node * [DOMDocument::createTextNode()](domdocument.createtextnode) - Create new text node php The Locale class The Locale class ================ Introduction ------------ (PHP 5 >= 5.3.0, PHP 7, PHP 8, PECL intl >= 1.0.0) A "Locale" is an identifier used to get language, culture, or regionally-specific behavior from an API. PHP locales are organized and identified the same way that the CLDR locales used by ICU (and many vendors of Unix-like operating systems, the Mac, Java, and so forth) use. Locales are identified using RFC 4646 language tags (which use hyphen, not underscore) in addition to the more traditional underscore-using identifiers. Unless otherwise noted the functions in this class are tolerant of both formats. Examples of identifiers include: * en-US (English, United States) * zh-Hant-TW (Chinese, Traditional Script, Taiwan) * fr-CA, fr-FR (French for Canada and France respectively) The Locale class (and related procedural functions) are used to interact with locale identifiers--to verify that an ID is well-formed, valid, etc. The extensions used by CLDR in UAX #35 (and inherited by ICU) are valid and used wherever they would be in ICU normally. Locales cannot be instantiated as objects. All of the functions/methods provided are static. The null or empty string obtains the "root" locale. The "root" locale is equivalent to "en\_US\_POSIX" in CLDR. Language tags (and thus locale identifiers) are case insensitive. There exists a canonicalization function to make case match the specification. Class synopsis -------------- class **Locale** { /\* Methods \*/ ``` public static acceptFromHttp(string $header): string|false ``` ``` public static canonicalize(string $locale): ?string ``` ``` public static composeLocale(array $subtags): string|false ``` ``` public static filterMatches(string $languageTag, string $locale, bool $canonicalize = false): ?bool ``` ``` public static getAllVariants(string $locale): ?array ``` ``` public static getDefault(): string ``` ``` public static getDisplayLanguage(string $locale, ?string $displayLocale = null): string|false ``` ``` public static getDisplayName(string $locale, ?string $displayLocale = null): string|false ``` ``` public static getDisplayRegion(string $locale, ?string $displayLocale = null): string|false ``` ``` public static getDisplayScript(string $locale, ?string $displayLocale = null): string|false ``` ``` public static getDisplayVariant(string $locale, ?string $displayLocale = null): string|false ``` ``` public static getKeywords(string $locale): array|false|null ``` ``` public static getPrimaryLanguage(string $locale): ?string ``` ``` public static getRegion(string $locale): ?string ``` ``` public static getScript(string $locale): ?string ``` ``` public static lookup( array $languageTag, string $locale, bool $canonicalize = false, ?string $defaultLocale = null ): ?string ``` ``` public static parseLocale(string $locale): ?array ``` ``` public static setDefault(string $locale): bool ``` } Predefined Constants -------------------- **`Locale::DEFAULT_LOCALE`** (null) Used as locale parameter with the methods of the various locale affected classes, such as NumberFormatter. This constant would make the methods to use default locale. These constants describe the choice of the locale for the getLocale method of different classes. **`Locale::ACTUAL_LOCALE`** (string) This is locale the data actually comes from. **`Locale::VALID_LOCALE`** (string) This is the most specific locale supported by ICU. These constants define how the Locales are parsed or composed. They should be used as keys in the argument array to [locale\_compose()](locale.composelocale) and are returned from [locale\_parse()](locale.parselocale) as keys of the returned associative array. **`Locale::LANG_TAG`** (string) Language subtag **`Locale::EXTLANG_TAG`** (string) Extended language subtag **`Locale::SCRIPT_TAG`** (string) Script subtag **`Locale::REGION_TAG`** (string) Region subtag **`Locale::VARIANT_TAG`** (string) Variant subtag **`Locale::GRANDFATHERED_LANG_TAG`** (string) Grandfathered Language subtag **`Locale::PRIVATE_TAG`** (string) Private subtag See Also -------- * [» RFC 4646 - Tags for Identifying Languages](http://www.faqs.org/rfcs/rfc4646) * [» RFC 4647 - Matching of Language Tags](http://www.faqs.org/rfcs/rfc4647) * [» Unicode CLDR Project:Common Locale Data Repository](http://www.unicode.org/cldr/) * [» IANA Language Subtags Registry](http://www.iana.org/assignments/language-subtag-registry) * [» ICU User Guide - Locale](https://unicode-org.github.io/icu/userguide/locale/) * [» ICU Locale api](http://www.icu-project.org/apiref/icu4c/uloc_8h.html#details) Table of Contents ----------------- * [Locale::acceptFromHttp](locale.acceptfromhttp) — Tries to find out best available locale based on HTTP "Accept-Language" header * [Locale::canonicalize](locale.canonicalize) — Canonicalize the locale string * [Locale::composeLocale](locale.composelocale) — Returns a correctly ordered and delimited locale ID * [Locale::filterMatches](locale.filtermatches) — Checks if a language tag filter matches with locale * [Locale::getAllVariants](locale.getallvariants) — Gets the variants for the input locale * [Locale::getDefault](locale.getdefault) — Gets the default locale value from the INTL global 'default\_locale' * [Locale::getDisplayLanguage](locale.getdisplaylanguage) — Returns an appropriately localized display name for language of the inputlocale * [Locale::getDisplayName](locale.getdisplayname) — Returns an appropriately localized display name for the input locale * [Locale::getDisplayRegion](locale.getdisplayregion) — Returns an appropriately localized display name for region of the input locale * [Locale::getDisplayScript](locale.getdisplayscript) — Returns an appropriately localized display name for script of the input locale * [Locale::getDisplayVariant](locale.getdisplayvariant) — Returns an appropriately localized display name for variants of the input locale * [Locale::getKeywords](locale.getkeywords) — Gets the keywords for the input locale * [Locale::getPrimaryLanguage](locale.getprimarylanguage) — Gets the primary language for the input locale * [Locale::getRegion](locale.getregion) — Gets the region for the input locale * [Locale::getScript](locale.getscript) — Gets the script for the input locale * [Locale::lookup](locale.lookup) — Searches the language tag list for the best match to the language * [Locale::parseLocale](locale.parselocale) — Returns a key-value array of locale ID subtag elements * [Locale::setDefault](locale.setdefault) — Sets the default runtime locale php fscanf fscanf ====== (PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8) fscanf — Parses input from a file according to a format ### Description ``` fscanf(resource $stream, string $format, mixed &...$vars): array|int|false|null ``` The function **fscanf()** is similar to [sscanf()](function.sscanf), but it takes its input from a file associated with `stream` and interprets the input according to the specified `format`. Any whitespace in the format string matches any whitespace in the input stream. This means that even a tab (`\t`) in the format string can match a single space character in the input stream. Each call to **fscanf()** reads one line from the file. ### Parameters `stream` A file system pointer resource that is typically created using [fopen()](function.fopen). `format` The interpreted format for `string`, which is described in the documentation for [sprintf()](function.sprintf) with following differences: * Function is not locale-aware. * `F`, `g`, `G` and `b` are not supported. * `D` stands for decimal number. * `i` stands for integer with base detection. * `n` stands for number of characters processed so far. * `s` stops reading at any whitespace character. * `*` instead of `argnum$` suppresses the assignment of this conversion specification. `vars` The optional assigned values. ### Return Values If only two parameters were passed to this function, the values parsed will be returned as an array. Otherwise, if optional parameters are passed, the function will return the number of assigned values. The optional parameters must be passed by reference. If there are more substrings expected in the `format` than there are available within `string`, **`null`** will be returned. On other errors, **`false`** will be returned. ### Examples **Example #1 **fscanf()** Example** ``` <?php $handle = fopen("users.txt", "r"); while ($userinfo = fscanf($handle, "%s\t%s\t%s\n")) {     list ($name, $profession, $countrycode) = $userinfo;     //... do something with the values } fclose($handle); ?> ``` **Example #2 Contents of users.txt** ``` javier argonaut pe hiroshi sculptor jp robert slacker us luigi florist it ``` ### See Also * [fread()](function.fread) - Binary-safe file read * [fgets()](function.fgets) - Gets line from file pointer * [fgetss()](function.fgetss) - Gets line from file pointer and strip HTML tags * [sscanf()](function.sscanf) - Parses input from a string according to a format * [printf()](function.printf) - Output a formatted string * [sprintf()](function.sprintf) - Return a formatted string
programming_docs