PHP 8.0: XMLWriter
objects replace xmlwriter
resources
As part of PHP's resource to object migration, XMLWriter extensions primitive resource
objects are now converted to accept and return the existing XMLWriter
objects.
XMLWriter
extension provides both an object-oriented interface and a procedural function interface.
-
The
XMLWriter
class contains all methods to work with the functionality provided by the extension. -
XMLWriter extensions procedural API, however, used
xmlwriter
resources and thexmlwriter
resource
must be passed as the first parameter to each function.
$writer = new XMLWriter();
$writer->openMemory();
$writer->startDocument("1.0");`
The same functionality in procedural code:
$writer_resource = xmlwriter_open_memory();
xmlwriter_start_document($writer_resource, '1.0');`
In PHP 8.0, the procedural-style functions accept and return XMLWriter
instead of resource
objects.
Object-oriented interface of
XMLWriter
extension has not changed in PHP 8.0. Furthermore, the procedural API functions are not deprecated.
Because the procedural-style functions accept XMLWriter
objects, it is possible to mix the object-oriented and procedural patterns. Note that this can make the code lose its consistency at no benefit. However, this can ease the migration to object-oriented API as the previous resource
objects are inter-changeable with the XMLWriter
objects
is_resource
Note that return values from the procedural API of XMLWriter extension will be standard PHP class objects, and will no longer return true
for is_resource
function calls.
It might be necessary to update existing code to accept XMLWriter
objects as well.
- is_resource($xw)
+ is_resource($xw) || $xw instanceof XMLWriter
However, this is an anti-pattern, because failing to create an xmlwriter
resource results in a false
return value in all PHP versions. A check against false
might be more appropriate:
- is_resource($xw) || $xw instanceof XMLWriter
+ !empty($xw)
Backwards Compatibility Impact
Unless there are is_resource
checks, this resource to object migration is completely opaque.
The object-oriented API continue to work, and the procedural API is not deprecated either. It not handles XMLWriter
objects that can be called interchangeably, as opposed to procedural-specific xmlwriter
resources.