0

I want to execute code everytime a apecific attribute is assiggned to a function.

For example:

<?php
#[Attribute]
class exampleAttribute
{
    public function __construct()
    {
        echo "exampleAttribute called";
    }
}

#[exampleAttribute()]
function exampleFunction()
{
    //...
}

But in this example the echo statement is never called. How do I do this?

0

1 Answer 1

1

Attributes are not instantiated automatically, because there is no particular time when they "become attached" - they are just part of the definition of that function, like the types and argument names.

Instead, you have to access them via reflection, as discussed in the PHP manual. Specifically, you would use a ReflectionFunction object to read the attribute, and then the newInstance method to instantiate it. Only when you do that will your echo line run.

Sign up to request clarification or add additional context in comments.

2 Comments

So, is there a way to get all funtions with a specific attribute?
@AaronJunker Not that I know of. I think the common approach is to have a script loop over everything, and generate a cache of sorts based on the results.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.