Is it possible to use mixins in php

前端 未结 5 2032
猫巷女王i
猫巷女王i 2020-12-08 19:33

I came to know about mixins.So my doubt is, is it possible to use mixins in php?If yes then how?

5条回答
  •  遥遥无期
    2020-12-08 20:38

    This answer is obsolete as of PHP 5.4. See Jeanno's answer for how to use traits.


    It really depends on what level of mixins you want from PHP. PHP handles single-inheritance, and abstract classes, which can get you most of the way.

    Of course the best part of mixins is that they're interchangeable snippets added to whatever class needs them.

    To get around the multiple inheritance issue, you could use include to pull in snippets of code. You'll likely have to dump in some boilerplate code to get it to work properly in some cases, but it would certainly help towards keeping your programs DRY.

    Example:

    class Foo
    {
      public function bar( $baz )
      {
        include('mixins/bar');
        return $result;
      }
    }
    
    class Fizz
    {
      public function bar( $baz )
      {
        include('mixins/bar');
        return $result;
      }
    }
    

    It's not as direct as being able to define a class as class Foo mixin Bar, but it should get you most of the way there. There are some drawbacks: you need to keep the same parameter names and return variable names, you'll need to pass other data that relies on context such as func_get_args_array or __FILE__.

提交回复
热议问题