Skip to content

Inconsistency in SplFileObject::fwrite $length Parameter Behavior #17228

Closed
@SigmaFlame

Description

@SigmaFlame

Bug Report: Inconsistency in SplFileObject::fwrite $length Parameter Behavior

Description:
The SplFileObject::fwrite method's signature is as follows:

public SplFileObject::fwrite(string $data, int $length = 0): int|false

The issue lies in the $length parameter. Unlike the fwrite function in PHP (which allows $length to be null to write the entire $data string), the SplFileObject::fwrite method does not accept null for $length. This creates inconsistency and forces developers to implement an unnecessary workaround.

Problem:

  1. If $length is passed as 0 (the default value), it writes 0 bytes to the file, contrary to the expectation that 0 would mean "write everything" (similar to the fwrite function).
  2. To bypass this behavior and write the full $data, one must write conditional logic:
    if (is_null($length)) {
        $written = $this->file->fwrite($data);
    } else {
        $written = $this->file->fwrite($data, $length);
    }

Expected Behavior:
The method should allow $length to be null to indicate that the full $data string should be written, consistent with the fwrite function.

Current Behavior:

  • $length = 0 writes 0 bytes, which is counterintuitive and unproductive.
  • Passing null for $length throws a type error.

Documentation Reference:
SplFileObject::fwrite documentation


Suggested Fix:
Update the method to allow $length to be null, aligning its behavior with the native fwrite function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions