Skip to content

Commit de00e63

Browse files
authored
smart_str: mention smart_str_extract()
Co-authored-by: George Peter Banyard <girgias@php.net> Co-authored-by: Christoph M. Becker <cmbecker69@gmx.de> Closes GH-127.
1 parent 5a9d168 commit de00e63

File tree

1 file changed

+20
-1
lines changed

1 file changed

+20
-1
lines changed

Book/php7/internal_types/strings/smart_str.rst

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,21 @@ parameter you'll use::
7070
/* Don't forget to release/free it */
7171
smart_str_free(&my_str);
7272

73+
We can also use the embedded ``zend_string`` independently of the ``smart_str``::
74+
75+
smart_str my_str = {0};
76+
77+
smart_str_appends(&my_str, "Hello, you are using PHP version ");
78+
smart_str_appends(&my_str, PHP_VERSION);
79+
80+
zend_string *str = smart_str_extract(my_str);
81+
RETURN_STR(str);
82+
83+
/* We must not free my_str in this case */
84+
85+
``smart_str_extract()`` returns a pre-allocated empty string if ``smart_str.s``
86+
is ``NULL``. Otherwise, it adds a trailing *NUL* byte and trims the allocated
87+
memory to the string size.
7388

7489
We used here the simple API, the extended one ends with ``_ex()``, and allows you to tell if you want a persistent or
7590
a request-bound allocation for the underlying ``zend_string``. Example::
@@ -92,7 +107,11 @@ smart_str specific tricks
92107
* Never forget to finish your string with a call to ``smart_str_0()``. That puts a *NUL* char at the end of the embed
93108
string and make it compatible with libc string functions.
94109
* Never forget to free your string, with ``smart_str_free()``, once you're done with it.
95-
* ``smart_str`` embeds a ``zend_string``, and then allows you to share that later elsewhere playing with its reference
110+
* Use ``smart_str_extract()`` to get a standalone ``zend_string`` when you have
111+
finished building the string. This takes care of calling ``smart_str_0()``,
112+
and of optimizing allocations. In this case, calling ``smart_str_free()`` is
113+
not necessary.
114+
* You can share the standalone ``zend_string`` later elsewhere playing with its reference
96115
counter. Please, visit the :doc:`zend_string dedicated chapter <zend_strings>` to know more about it.
97116
* You can play with ``smart_str`` allocations. Look at ``smart_str_alloc()`` and friends.
98117
* ``smart_str`` is heavily used into PHP's heart. For example, PHP's

0 commit comments

Comments
 (0)