Hello i have a problem in OOP PHP. I try override constructor from superclass to subclass with array parameter in it. This is my superclass code :
<?php
class Person
{
private $firstName;
private $lastName;
private $gender;
private $dob;
private $address;
private $country;
private $phone;
private $occupation;
public function __construct($array) {
foreach($array as $key => $value) {
$this->$key = $value;
}
}
public function setFirstName($firstName) {
$this->firstName = $firstName;
}
public function getFirstName() {
return $this->firstName;
}
// Another Getter and Setter
// ...
And this is my subclass code :
<?php
class Register extends Person
{
private $nickName;
private $email;
public function __construct($array) {
parent::__construct($array);
}
// Getter and Setter
// ...
But when i try to access nickName and email, i get an error like this :
Fatal error: Cannot access private property Register::$email in C:\xampp\htdocs\php\oop\class\person.class.php on line 16
And this is my test code :
<?php
function __autoload($myClass) {
require_once 'class/' . $myClass . '.class.php';
}
$data = array(
'firstname' => $_POST['first_name'],
'lastname' => $_POST['last_name'],
'nickname' => $_POST['nick_name'],
'gender' => $_POST['gender'],
'dob' => $_POST['dob'],
'address' => $_POST['address'],
'zipcode' => $_POST['zipcode'],
'country' => $_POST['country'],
'phone_number' => $_POST['phone_number'],
'email' => $_POST['email'],
'occupation' => $_POST['occupation']
);
$account = new Register($data);
echo $account->getFirstName();
// Proses DB
// $db->insert($account);
?>
Any Sugesstion? Thank you.
Answer :
I already find solutions. Key name in array must same with class property.
In array i write firstname
and property firstName
, the correct way is firstName
in both, array and property.