Do understand some code using abstract class in php
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 passwordTo 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:
if( array_key_exists( $key, $this->data ))
$this->data[$key] = $value;
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.
Looks like since I did not create a constructor for the extended class is calling implicitly the father class, right?
Not implicitly, but explictly. By "not creating a constructor" you didn't override the existing one.
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.
Yes. Because in the parent class you define, that the value should only be set, if the key exists, the non-existing key "usernames" is silently omitted.
精彩评论