Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Undefined method in traits #9

Closed
Vrtak-CZ opened this issue Jul 22, 2016 · 4 comments
Closed

Undefined method in traits #9

Vrtak-CZ opened this issue Jul 22, 2016 · 4 comments

Comments

@Vrtak-CZ
Copy link

Example code:

trait MyTrait
{
  public function foo()
  {
    return $this->bar();
  }
}

Call to an undefined method MyTrait::bar().

@ondrejmirtes
Copy link
Member

This actually points out problem in your code 😊 If you use the trait in a
class without the bar method, the trait code will crash.

Correct solution is to define the bar method in the trait as abstract so
the trait can be used only in classes that define the bar method.

I want to write an article about this - we have several traits used by
presenters and controls, so I had to define methods like flashMessage and
redirect as abstract in the traits so they can be used only by the right
classes.

On Friday, 22 July 2016, Patrik Votoček notifications@github.com wrote:

Example code:

trait MyTrait{ public function foo() { return $this->bar(); }}

Call to an undefined method MyTrait::bar().


You are receiving this because you are subscribed to this thread.
Reply to this email directly, view it on GitHub
#9, or mute the thread
https://github.com/notifications/unsubscribe-auth/AAGZuEcPh1Hy8qWkWNrKWyR09r_wRbdmks5qYBn3gaJpZM4JSXFl
.

Ondřej Mirtes

@Vrtak-CZ
Copy link
Author

Thank you. I know it's a bad idea to ignore not implemented methods in traits. It's first time when I use traits in my project.

Abstract function is a good idea. I'll try it.

@JanTvrdik
Copy link
Contributor

@ondrejmirtes imho using abstract methods in traits is more hack than a solution because it does not actually enforce existence of the method with the same signature. You would need sth like https://docs.hhvm.com/hack/other-features/trait-and-interface-requirements

@ondrejmirtes
Copy link
Member

@JanTvrdik I didn't know the signature isn't enforced (https://3v4l.org/YHMU0) but I still think the approach with abstract methods in traits is better than nothing at all...

@lock lock bot locked as resolved and limited conversation to collaborators Dec 21, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants