first off I'm totally new to oop, so apologies for the bad code.
I've written a PHP script that returns a JSON object (based on mock data atm but will use a db later on) I have an ajax function on the front end that recieves the JSON data and turns it into a table.. The script it working totally fine.. But, as I say, I'm new to OOP and trying to get as much info as I can in writing good OOP.. Do you have any pointers as to how I can improve my code? I know I can make some improvements on error checking, but I'm looking for any guidance you can give on good OOP design.
<?php
class Person
{
public function __construct()
{
}
function __set($property, $value)
{
$this->$property = $value;
}
function __get($property)
{
if (isset($this->$property)) {
return $this->$property;
}
}
public function getArrayData()
{
$arr = array();
foreach (get_object_vars($this) as $name => $value) {
if ($name == 'department' && $value == 'admin') {
$value = '';
}
$arr[$name] = $value;
}
return $arr;
}
}
class handleData
{
public $_data;
public function __construct($data)
{
$this->_data = $data;
$this->_dataArr = array();
for ($x = 0; $x < count($this->_data); $x++) {
$this->_dataArr[$x] = serialize($this->_data[$x]);
}
}
public function getJSON()
{
foreach ($this->_dataArr as $value) {
$object = unserialize($value);
$obj[] = $object->getArrayData();
}
$data = array(
'people' => $obj
);
return json_encode($data);
}
}
$name1 = new Person();
$name1->name = 'mark';
$name1->email = '[email protected]';
$name1->photo = 'mark.jpg';
$name1->department = 'admin';
$name2 = new Person();
$name2->name = 'steve';
$name2->email = '[email protected]';
$name2->photo = 'steve.jpg';
$name2->department = 'marketing';
$mydata = new handleData(Array(
$name1,
$name2,
$name3,
$name4
));
echo $mydata->getJSON();