Skip to content

Add #[NoSerialize] attribute support to prevent property serialization.#20074

Draft
dkulyk wants to merge 12 commits intophp:masterfrom
dkulyk:no_serializable_attr
Draft

Add #[NoSerialize] attribute support to prevent property serialization.#20074
dkulyk wants to merge 12 commits intophp:masterfrom
dkulyk:no_serializable_attr

Conversation

@dkulyk
Copy link
Copy Markdown

@dkulyk dkulyk commented Oct 6, 2025

RFC: https://wiki.php.net/rfc/no_serialize_attribute

This PR introduces a new attribute, #[NoSerialize], that can be
applied to class properties to explicitly exclude them from
serialization when using PHP’s built-in serialization mechanisms.

Motivation

When developing complex objects, it’s often necessary to exclude
specific properties from serialization — for example, resources,
closures, database connections, or transient caches.
Currently, developers must manually implement __serialize() /
__sleep() to filter these properties, which can lead to boilerplate
code and potential maintenance errors.

Adding a native attribute would provide a simple and declarative way
to express this intention directly in code.

class Example
{
    public string $name;

    #[NoSerialize]
    public $connection; // e.g., PDO, socket, or any transient resource
}

When serialize($example) is called, $connection would be excluded automatically.

Benefits

  • Reduces boilerplate for common use cases.
  • Makes serialization intent explicit and self-documenting.
  • Simplifies framework and library code that relies on serialization

@dkulyk
Copy link
Copy Markdown
Author

dkulyk commented Oct 6, 2025

@TimWolla
Copy link
Copy Markdown
Member

Should this be closed in favor of #20163?

@dkulyk
Copy link
Copy Markdown
Author

dkulyk commented Oct 20, 2025

Should this be closed in favor of #20163?

Those are different RFCs.

#20163 forbids class to serialization.
This PR/RFC allows ignore properties or objects on serialization.

I'm working on the 3rd RFC, which should logically gather all these things.

@calebdw
Copy link
Copy Markdown

calebdw commented Mar 13, 2026

@dkulyk, any update on this? I was looking for such an attribute so I didn't have to overload __sleep and I came across this---would be very useful!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants