Skip to content

Instantly share code, notes, and snippets.

@kobus1998
Last active January 5, 2021 15:15
Show Gist options
  • Select an option

  • Save kobus1998/d0027c0c1f3ee5a9bdccebb29565f4d4 to your computer and use it in GitHub Desktop.

Select an option

Save kobus1998/d0027c0c1f3ee5a9bdccebb29565f4d4 to your computer and use it in GitHub Desktop.
Export trait
<?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