I am trying to isolate the attributes of an originating class
in an included trait
. IE The trait
should make an array of the names of all the attributes of the class
but not the attributes of the trait
for use within the trait
.
I have tried doing this by extending
a class. I have tried using static
methods as per PHP: Is it possible to get the name of the class using the trait from within a trait static method? and I am getting nowhere.
I am about to use known attributes in the trait
and simply remove them from the attribute array (as I know their names). This is a rather ugly solution but it will work.
Anyone see a better way to do this?
trait FooTrait
{
public $classVariables;
public function classAttributes()
{
$callingClass = get_class($this);
$rawAttributes= $this->$classVariables = get_class_vars($callingClass);
var_dump($rawAttributes);
var_dump($callingClass);
return $rawAttributes;
}
public function info()
{
var_dump($this->classVariables);
}
// manipulate $this -> classVaribales to do generic database operations
}
class Mine
{
use FooTrait;
protected $attrib1;
protected $attrib2;
protected $attrib3;
}
$needed = new Mine;
$needed->classAttributes();
$needed->info();
OUTPUT is attribute 1,2,3 and bar. How do I get just attribute 1, 2, 3?
EDIT: I edited a couple of attributes to try and make it more comprehensible.
UPDATE: This does not work if trait
attributes are protected
or private
. As traits should not be directly referenced ... bit of a deal breaker.
The only way I could find to get the attributes of the trait
WITHOUT those of the calling class
was to name it as a literal. BUT that limits the scope
and so cannot see the private
and protected
attributes.
I am giving up at this point and will use an array of the names of attributes used in the trait
. Not a big problem just massively inelegant.
class ThisClass {
use ThisTrait;
public $classAttribute1 = 3;
public $classAttribute2 = 3;
public $classAttribute3 = 3;
}
trait ThisTrait {
public $traitTrait1 = 3;
public $traitTrait2 = 3;
public $traitTrait3 = 3;
public function classAttributes (){
$traitAttributes = get_class_vars("ThisTrait"); //NB String not variable
$traitAttributes = array_keys ($traitAttributes);
$className = get_class($this); //NB Var = gets class where this called
$classAttributes = get_class_vars($className);
$classAttributes = array_keys($classAttributes);
$classOnly = array_diff($classAttributes, $traitAttributes);
return $classOnly;
}
}
$thisClass = new ThisClass ();
$result = $thisClass -> classAttributes();
var_dump($result);
=========================================
array (size=3)
0 => string 'classAttribute1' (length=15)
1 => string 'classAttribute2' (length=15)
2 => string 'classAttribute3' (length=15)