Last active
November 3, 2023 06:34
-
-
Save yugo412/c3f608a1656b6f5e9e52b037db7c30cc to your computer and use it in GitHub Desktop.
Fungsi berantai (chained method/function) pada PHP.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Simple chained method in PHP | |
* | |
* @link http://laravel.web.id/tips-trik/membuat-fungsi-berantai-chained-methodfunction-di-php/ | |
* @copyright 2016 | |
*/ | |
class User { | |
/** | |
* Users Name | |
* | |
* @var string | |
*/ | |
private $name = null; | |
/** | |
* User Email | |
* | |
* @var string | |
*/ | |
private $email = null; | |
public function __construct($data = null) | |
{ | |
// set default data | |
if (! empty($data)) { | |
foreach ($data as $key => $value) { | |
if (property_exists($this, $key)) { | |
$this->$key = $value; | |
} | |
} | |
} | |
} | |
/** | |
* Return data as JSON formatted using json() method | |
* | |
* @return string | |
*/ | |
public function __toString() | |
{ | |
return $this->json(); | |
} | |
/** | |
* Set default name | |
* | |
* @param string $name | |
* @return object | |
*/ | |
public function setName($name) | |
{ | |
$this->name = $name; | |
return $this; | |
} | |
/** | |
* Set default email | |
* | |
* @param string $email | |
* @return object | |
*/ | |
public function setEmail($email) | |
{ | |
$this->email = $email; | |
return $this; | |
} | |
/** | |
* Return as JSON formatted string | |
* | |
* @return string | |
*/ | |
public function json() | |
{ | |
return json_encode([ | |
'name' => $this->name, | |
'email' => $this->email | |
]); | |
} | |
} | |
// simple function | |
if (! function_exists('user')) { | |
function user($user = null) { | |
return new User($user); | |
} | |
} | |
// instance class | |
$user = new User; | |
echo $user->setName('Laravel.web.id') | |
->setEmail('mail@laravel.web.id') | |
->json(); | |
// simpler class instance | |
echo (new User)->setName('Laravel.web.id')->setEmail('mail@laravel.web.id')->json | |
// simple function | |
echo user()->setName('Laravel.web.id') | |
->setEmail('mail@laravel.web.id') | |
->json(); | |
// simple function with __construct | |
echo user(['name' => 'Laravel.web.id', 'email' => 'mail@laravel.web.id'])->json(); | |
// simple function with __construct and __toString | |
echo user(['name' => 'Laravel.web.id', 'email' => 'mail@laravel.web.id']); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment