Skip to content

Instantly share code, notes, and snippets.

@nahid
Last active January 25, 2017 21:20
Show Gist options
  • Save nahid/89bd04b1150fad022ae1469d133e1408 to your computer and use it in GitHub Desktop.
Save nahid/89bd04b1150fad022ae1469d133e1408 to your computer and use it in GitHub Desktop.
This gist is for PHP traits Example
<?php
trait Greetings
{
public function sayHello()
{
return 'Hello Bro';
}
public function goodBye()
{
return 'See you, good bye';
}
}
class NewGreetings
{
use Greetings;
public function sayHello()
{
return 'Hello again';
}
}
$greetings = new NewGreetings();
echo $greetings->sayHello(); // Output: Hello again
echo $greetings->goodBye(); // Output: See you, goodbye
<?php
class SumSub
{
public function sum($a, $b)
{
return $a + $b;
}
public function sub($a, $b)
{
return $a - $b;
}
}
// class for multiplication and division inherit from SubSub class
class MulDiv extends SumSub
{
public function mul($a, $b)
{
return $a * $b;
}
public function div($a, $b)
{
return $a / $b;
}
}
// calculator class
class Calculator extends MulDiv
{
public function square($a)
{
return $a * $a;
}
}
<?php
trait Authorizable
{
// write methods and properties here
}
<?php
trait Messagable
{
public function sendMessage($to, $message)
{
return $this->send($to, $message);
}
}
trait GroupMessage
{
use Messagable;
public function sendMessageToGroup($to, $message)
{
return $this->sendGroupMessage($to, $message);
}
}
<?php
trait SumSub
{
public function sum($a, $b)
{
return $a + $b;
}
public function sub($a, $b)
{
return $a - $b;
}
}
trait MulDiv
{
public function mul($a, $b)
{
return $a * $b;
}
public function div($a, $b)
{
return $a / $b;
}
}
class Calculator
{
use SumSub;
use MulDiv;
public function square($a)
{
return $a * $a;
}
}
<?php
$cal = new Calculator;
echo $cal->square(3);
echo $cal->sum(3, 4);
// the following output is 9 and 7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment