Skip to content

Instantly share code, notes, and snippets.

@demircan-s
demircan-s / example.php
Created January 8, 2020 15:20
Bad example of using callbacks
<?php
class Person{
private $surname = "Doe";
function getSurname(callable $fn){
return $fn($this->surname);
}
}
echo (new Person())->getSurname("strtoupper"); //DOE
<?php
require_once "vendor/autoload.php";
function printStatus(CharacterUndoDecorator $decorator)
{
list('x' => $x,'y' => $y,'speed' => $speed) = $decorator->getXYAndSpeed();
echo "Current Status: x:{$x}, y:{$y}, speed:{$speed}" . "<br> \n";
}
function undoAndPrint(CharacterUndoDecorator $decorator)
<?php
class CharacterUndoDecorator implements CharacterInterface
{
private CharacterInterface $character;
private array $undoStack = [];
public function __construct(CharacterInterface $character)
{
<?php
class Human implements CharacterInterface
{
private int $x,$y,$speed;
public function __construct(int $x = 0,int $y = 0,int $speed = 3)
{
$this->x = $x;
$this->y = $y;
<?php
class Bird implements CharacterInterface
{
private int $x,$y,$speed;
public function __construct(int $x = 0,int $y = 0,int $speed = 5)
{
$this->x = $x;
<?php
interface CharacterInterface
{
public function moveInXAxis(int $times): void;
public function moveInYAxis(int $times): void;
public function changeSpeed(int $change): void;
<?php
$math = function(int ...$args) : array{
$operations = [];
$operations["Addition"] = function() use ($args){
$result = 0;
foreach($args as $val)
$result += $val;
return $result;
@demircan-s
demircan-s / Anonymous.php
Created December 25, 2019 23:19
An anonymous function is a Closure as well
<?php
function hello(){
return function() {
echo "Hello";
};
}
echo get_class( hello() ); // Closure
<?php
//It takes a function as an argument
function execute(callable $myFunc)
{
$myFunc();
}
//Prints "Hello there!"
execute(function(){
echo "Hello there!";
<?php
function sum(int ...$args){
$sumVal = 0;
for($i = 0;$i < count($args);$i++)
$sumVal += $args[$i];
return $sumVal;
}