Last active
January 5, 2021 15:15
-
-
Save kobus1998/d0027c0c1f3ee5a9bdccebb29565f4d4 to your computer and use it in GitHub Desktop.
Export trait
This file contains hidden or 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 | |
| trait export | |
| { | |
| public static function getHeader() | |
| { | |
| $sCsv = ''; | |
| foreach(get_class_vars(self::class) as $key => $value) { | |
| $sCsv .= $key . ','; | |
| } | |
| $sCsv = trim($sCsv, ',') . "\n"; | |
| return $sCsv; | |
| } | |
| public function toCsv() | |
| { | |
| $sCsv = ''; | |
| foreach($this as $key => $value) { | |
| $sCsv .= $value . ','; | |
| } | |
| $sCsv = trim($sCsv, ',') . "\n"; | |
| return $sCsv; | |
| } | |
| } | |
| class U { | |
| use export; | |
| public $name; | |
| public $lastName; | |
| public function __construct($name, $lastName) { | |
| $this->name = $name; | |
| $this->lastName = $lastName; | |
| } | |
| } | |
| $csv = U::getHeader(); | |
| foreach ([new U("a", "b"), new U("c", "d"), new U("e", "f")] as $u) { | |
| $csv .= $u->toCsv(); | |
| } | |
| echo $csv; | |
| /* | |
| name,lastName | |
| a,b | |
| c,d | |
| e,f | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment