我來自.NET世界。現在進入這些寒冷的PHP水域。Php繼承,動態屬性和新的靜態()構造函數
我發現一個讓我有點困惑的例子。當然,我正在嘗試將OOP基礎應用於此PHP代碼,但它沒有任何意義。
這是我正在談論的課程。
<?php
namespace app\models;
class User extends \yii\base\Object implements \yii\web\IdentityInterface
{
public $id;
public $username;
public $password;
public $authKey;
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
],
];
public static function findIdentity($id)
{
return isset(self::$users[$id]) ? new static(self::$users[$id]) : null;
}
public static function findByUsername($username)
{
foreach (self::$users as $user) {
if (strcasecmp($user['username'], $username) === 0) {
return new static($user);
}
}
return null;
}
public function getId()
{
return $this->id;
}
public function getAuthKey()
{
return $this->authKey;
}
public function validateAuthKey($authKey)
{
return $this->authKey === $authKey;
}
public function validatePassword($password)
{
return $this->password === $password;
}
}
好吧,很明顯,我認爲在方法findByIdentity($ id)的所有它做的是創造用戶的靜態新實例。這是第一件讓我措手不及的事情。
在.net中,您無法創建靜態類的實例。
現在,繼續。在那一行
return isset(self::$users[$id])? new static(self::$users[$id]) : null;
第二件讓我感興趣的事情是以下幾點。
既然你數組中有一個鍵/值集合....
private static $users = [
'100' => [
'id' => '100',
'username' => 'admin',
'password' => 'admin',
'authKey' => 'test100key',
],
'101' => [
'id' => '101',
'username' => 'demo',
'password' => 'demo',
'authKey' => 'test101key',
],
];
如何PHP決定了其具有創建一個用戶對象?反射?這導致我到下一個問題....看看它繼承的類,Object,在構造函數中,有一個參數是一個數組(上面數組的一個元素)。
public function __construct($config = [])
{
if (!empty($config)) {
Yii::configure($this, $config);
}
$this->init();
}
,但這個類在其構造,呼籲的Yii ::配置($此,$配置),並在此方法中,我看到它的方式,Yii中也加入到了這個$(對象實例我我假設,而不是用戶之一)屬於用戶的參數。
public static function configure($object, $properties)
{
foreach ($properties as $name => $value) {
$object->$name = $value;
}
return $object;
}
對我來說似乎是動態地將參數添加到Object中,這將通過匹配參數由User訪問。
有意義嗎?
從我的角度看.NET,$此在對象是指對象實例本身,而不是給用戶實例從它繼承(像我朋友說的)。我告訴他這違反了基本的面向對象原則,這根本不可能。
任何能夠讓我明白這一點的人?
謝謝。
鏈接只有答案是不歡迎的SO。最好在答案中包含重要部分,因爲鏈接可能會在某個時候死亡。 – arogachev