[英]OOP Classes, how to put class in class
我已經開始學習OOP,並且建立了一個名為accountactions的類,我想知道我是否寫得很好。
該類位於文件accountactions.class.php中。
<?php
class accountactions(){
public function register($login, $password, $email){
//Zapisujemy dane wysłane formularzem
$this->username = mysql_real_escape_string($login);
$this->password = mysql_real_escape_string($password);
$this->email = mysql_real_escape_string($email);
//Hash password
$this->password = md5(sha1($this->password));
$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");
}
}
?>
register.php文件:
<?php
require_once("accountactions.class.php");
$account = new accountactions();
$account->register('samplelogin', 'samplepassword', 'sample@email');
?>
我對此片段有一些疑問:
$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");
如何將數據庫類加入帳戶類?
我想保留一個模型,可以執行以下操作:
$ account-> register('$ _ POST ['login']','$ _POST ['password']','$ _POST ['email']');
除非有更好的方法可以做到這一點。
我是OOP的新手,因此感謝所有技巧和指導。
該代碼主要是好的,但是有些事情我認為很糟糕。 首先,我認為您應該遵循一些命名約定,因為accountactions是一個不好的名字。 對於OOP,我認為您應該使用一些駝峰形式(因此,accountActions或AccountActions-建議您使用后者)。 然后,在類名之后不應包含括號。 我還建議您將每個大括號放在單獨的行中,但這取決於您的個人喜好。 然后,您的第一個評論要用波蘭語寫出來-我建議您始終用英語寫所有評論,變量名等,因為每個人都可以理解。 然后在register方法中,您將變量分配給class的屬性,但是您之前沒有聲明過它們(或者至少沒有在代碼中向我們展示過)。 同樣在插入查詢中,您嘗試將emtpy字符串''插入id字段(我假設它是具有auto_increment的唯一,非空無符號整數-如果是,則不應在查詢中包括它)。 我會這樣寫你的代碼:
class AccountActions
{
protected $Username;
protected $Password;
protected $Email;
protected $DB;
public function __construct()
{
$this->DB = //instantiate your database driver of choice here, e.g. mysqli
}
public function register($Username, $Password, $Email)
{
//We escape the provided values and populate the object's properties with them
$this->Username = mysql_real_escape_string($Login);
$this->Password = mysql_real_escape_string($Password);
$this->Email = mysql_real_escape_string($Email);
//Hash password
$this->Password = md5(sha1($this->Password));
$Query = "INSERT INTO radio_users(username, password, email)
VALUES('$this->Username', '$this->Password', '$this->Email')";
$this->DB->simplequery($Query);
}
}
如何將數據庫類加入帳戶類?
不確定您的意思是什么,但是如果您想訪問類中的某些數據庫驅動程序,則應添加一個屬性,該屬性將存儲數據庫驅動程序並將其實例化在構造函數中(或者您可能具有一個靜態屬性,該屬性將包含數據庫驅動程序)。
同樣也不確定標題問題中的含義-如果要使用內部類(在其他類中聲明的類)-PHP中不提供它們。
我也鼓勵您在學習了基本的OOP之后選擇一些PHP框架-Zend Framework是我的最愛。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.