PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, March 14, 2022

[FIXED] Having a Trait in multiple class

 March 14, 2022     codeigniter, php, traits     No comments   

Issue

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';


Answered By - Rahil Wazir
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing