Search code examples
phpcodeignitertraits

Having a Trait in multiple class


Maybe I'm not getting the whole trait system so I thought I'd ask StackOverFlow.

I made my first trait...

<?php
trait MY_Stat
{   
  var $dex;
  var $int;
  var $str;
}
?>

I can't manage to make it work with my class whatsoever ( in another file ) ....

class MY_Mobile
{
  use MY_Stat;

  public function __construct($params = NULL)
  {     
    var_dump($this);
  }
}

I'm always hitting this wall :

Fatal error: Trait 'MY_Trait' not found in ...\wamp\www\game\application\libraries\MY_Mobile.php

I would like to have this trait in many classes, namely, Mobiles, Items, etc... Am I supposed to have the definition of the trait in the same file as the class ?

On a sidenote, if you're using codeigniter, how did you manage to make it load, are you setting your traits into a helper file, library file... ?


Solution

  • Well you can workout this problem by doing something like this:

    Path:

    application/helpers/your-trait-class.php

    Contents:

    <?php
    if (!trait_exists('MY_Stat')) {
        trait MY_Stat
        {
            public $dex;
            public $int;
            public $str;
        }
    }
    

    In your library just include the trait class (as i said) manually. After the !defined('BASEPATH'); line.

    Your Library:

    include APPPATH . 'helpers/your-trait-class.php';
    
    class YourLibrary {
        use MY_Stat;
    

    and use trait class properties within your library methods like this:

    $this->dex = 0.1;
    $this->int = 1;
    $this->str = 'Hello';