Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merging behavioral methods to a PHP class

Tags:

oop

php

abstract

Let's say i have the following behavior and standard class:

abstract class MyBehavior {
     function testFunction(){
         return 'test';
     }
}

class TestClass {
     var $use = array('MyBehavior');

     function __construct(){
         // do something to give me access to function testFunction through
         // $this->testFunction();
     }
}

$test = new TestClass();

As i commented, i would like the MyBehavior method to be available inside TestClass ($test->testFunction();) without "extending" the class...

Is this possible?

EDIT: Thanks for all the responses, I have my answer, or at least i need to know what my options are, so thanks! I can only give one right answer, so I'm going with the first response.

like image 615
Tobias Hagenbeek Avatar asked Jan 27 '26 05:01

Tobias Hagenbeek


1 Answers

<?php

trait MyBehavior {

    public function testFunction() 
    {
        return 'test';
    }

}

class TestClass {

    use MyBehavior;

    function __construct()
    {
        echo $this->testFunction();
    }

}

$test = new TestClass();

You could use a trait to add your desired behavior to a class. Traits exist since PHP >= 5.4.0 and are a neat way to extend classes without actually making use of inheritance. But be careful:

If misused, traits will be in your way more than they help you. Anthony Ferrera wrote a really good blogpost about the downsides of traits. So you should definitely give it a read.

like image 128
thpl Avatar answered Jan 29 '26 19:01

thpl