我通过PDO访问我的MySQL数据库.我正在设置对数据库的访问权限,我的第一次尝试是使用以下内容:
我想到的第一件事是global:
$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'root', 'pwd');
function some_function() {
global $db;
$db->query('...');
}
Run Code Online (Sandbox Code Playgroud)
这被认为是一种不好的做法.一点点搜索后,我结束了与Singleton模式,其
"适用于需要单个类实例的情况."
根据手册中的示例,我们应该这样做:
class Database {
private static $instance, $db;
private function __construct(){}
static function singleton() {
if(!isset(self::$instance))
self::$instance = new __CLASS__;
return self:$instance;
}
function get() {
if(!isset(self::$db))
self::$db = new PDO('mysql:host=127.0.0.1;dbname=toto', 'user', 'pwd')
return self::$db;
}
}
function some_function() {
$db = Database::singleton();
$db->get()->query('...');
}
some_function();
Run Code Online (Sandbox Code Playgroud)
当我能做到这一点时,为什么我需要相对较大的课程呢?
class Database {
private static $db;
private function __construct(){}
static function get() …Run Code Online (Sandbox Code Playgroud) 我正在查看Drupal 7的来源,我找到了一些我以前没见过的东西.我做了一些初步查看php手册,但它没有解释这些例子.
关键字static对函数内部的变量做了什么?
function module_load_all($bootstrap = FALSE) {
static $has_run = FALSE
Run Code Online (Sandbox Code Playgroud) 类是这样做的吗?
Class Main
{
$this->a = new A();
$this->b = new B();
$this->c = new C();
$this->b->doTranslate($this->a->saySomething());
}
Run Code Online (Sandbox Code Playgroud)
这就是特质的作用,不是吗?
Class Main {
use A;
use B;
use C;
$this->doTranslate($this->saySomething());
}
Run Code Online (Sandbox Code Playgroud)
我对特征根本没有太多了解,但通过查看新的 PHP 5.4 特征示例,它们似乎只在单一情况下有帮助。A class only be extended once to use $this together, but we can use multiple traits.
问题 1:这是使用特征相对于基本类的唯一优势吗?
问题2:如果trait A, B, and C都有一个名为 的函数example(),当我尝试$this->example();PHP 将如何确定将使用哪个特征?将会发生什么?
此外,不要写一堵文字墙;只需向我提供一个简短的代码示例和一个简短的简介,我可以查看并理解。我不熟悉特质,也不知道它们到底是什么。