I understand the concept of abstract class, but I saw a code in a book that I do not understand.
I will short the code and would like you help me to understand, I know what it does I just don’t why is working.
Here I declared and abstract class DataObject and its contructor
abstract class DataObject {
protected $data = array();
public function __construct( $data ){
foreach ( $data as $key => $value )
{
if( array_key_exists( $key, $this->data ))
$this->data[$key] = $value;
}
}
}
Then I have this
class Member extends DataObject {
protected $data = array(
"username" => "",
"password" => ""
);
public function getInfo(){
echo "Usernarme: " . $this->data["username"] . " <br/>password: " . $this->data["password"];
}
}
So when I do this
$m= new Member( array(
"username" => "User",
"password" => "Some password" )
);
$m->getInfo();
I get
Usernarme: User
password: Some password
To be more specific.
-
Looks like since I did not create a constructor for the extended class is calling implicitly the father class, right?
-
How the constructor works in a way that it is validating the data array according to the Member array values?, I mean if when I create the Object
$m= new Member( array(
“username” => “User”,
“password” => “Some password” )
);
Change the key “username” for “usernames” it won’t assign the value “User” for example.
Thanks
In the parent constructor:
This prevents it from creating new keys. In the child class the keys “username” and “password” are defined, so those are the only keys that the constructor will allow to be written.