-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtraitcorrect.php
More file actions
55 lines (46 loc) · 928 Bytes
/
traitcorrect.php
File metadata and controls
55 lines (46 loc) · 928 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<?php
$file = __FILE__;
include 'highlight.php';
trait ArrayConverter {
public function toArray()
{
$props = array();
foreach ($this as $name => $value) {
if (is_object($value)) {
$properties[$name] = $value->toArray();
} else {
$properties[$name] = $value;
}
}
return $properties;
}
}
trait JsonConverter {
public function toJson()
{
return json_encode($this);
}
}
class Book {
use JsonConverter, ArrayConverter;
public $title;
public $isbn;
public $author;
}
class Author {
use JsonConverter, ArrayConverter;
public $name;
}
$author = new Author;
$author->name = 'Herman Melville';
$mybook = new Book;
$mybook->title = 'Moby-Dick';
$mybook->author = $author;
$mybook->isbn = '123456789012345';
echo '<pre>';
print_r($mybook->toArray());
echo "\n";
echo $mybook->toJson();
echo "\n";
echo $author->toJson();
echo '</pre>';