php trait 使用另一个 trait

标签 php class oop traits

我有一个特征正在使用另一个特征,现在我收到关于类中不存在的函数的错误。 我简化了代码:

设置.php:

<?php
trait settings{
    protected function getSetting($type, $setting){ // read setting from config.ini
        try{
            $configFile=dirname(__FILE__)."/../config.ini";
            if(!file_exists($configFile)||!is_file($configFile))throw new Exception("Config file was not found. ");
            $configContents=parse_ini_file($configFile,true);
            if(is_array($configContents)&&array_key_exists($type,$configContents)&&is_array($configContents[$type])&&array_key_exists($setting,$configContents[$type]))return $configContents[$type][$setting];
            else throw new Exception("Setting ".$setting." could not be found in ".$type.".");
        }
        catch(Exception $e){throw new Exception($e->getMessage());}
    }
}
?>

数据库.php

<?php
trait database{
    use settings,session;
    private $pdo;
    protected function connect(){ // connect to database
        try{
            $this->pdo=new PDO("mysql:host=".$this->getSetting("db","host").";dbname=".$this->getSetting("db","database"),$this->getSetting("db","user"),$this->getSetting("db","password"));
            $this->init();
        }
        catch(PDOException $e){throw new Exception($e->getMessage());}
    }
}
?>

用户.php

<?php
class users{
    use database;
    public function __construct(){
        try{
            $this->connect();
        }
        catch(Exception $e){throw new Exception($e->getMessage());}
    }
    public function __destruct(){
        unset($this);
    }
    public function isAdmin(){
        try{
            if($this->loginStatus()===true){

            }
            else return false;
        }
        catch(Exception $e){throw new Exception($e->getMessage());}
    }
    public function loginStatus(){
        if(!$this->getSession("tysus")||!$this->getSession("tyspw"))return false;// user is not logged in because we couldn't find session with username and/or password
        if(!$this->userExists($this->getSession("tysus"),$this->getSession("tyspw")))return false;// user is unknown to database
        return true;// other checks failed, user must be logged in
    }
}
?>

现在我收到这个错误:

Fatal error: Call to undefined method users::readSetting() in /home/deb2371/domains/nonamenohistory.com/public_html/include/classes/class.database.php on line 18

我认为会发生这样的事情: 类用户使用特征数据库,特征数据库将使用特征设置和特征 session 。

如果是这样,我就不会收到任何错误,但不幸的是,事实并非如此。

有人知道如何解决这个问题吗?

最佳答案

Code reuse is one of the most important aspects of object-oriented programming.

Multiple TraitsComposing Multiple Traits 的简单示例,您可以通过它轻松分析您的情况。

  1. 使用多个特征

一个类可以使用多个特征。以下示例演示如何在 IDE 类中使用多个特征。为了演示,它模拟了PHP中的C编译模型。

<?php

 trait Preprocessor{
 function preprocess() {
    echo 'Preprocess...done'. '<br/>';
  }
}
trait Compiler{
function compile() {
   echo 'Compile code... done'. '<br/>';
  }
}

trait Assembler{
function createObjCode() {
   echo 'Create the object code files... done.' . '<br/>';
 }
}

trait Linker{
function createExec(){
   echo 'Create the executable file...done' . '<br/>';
  }
}

class IDE{
use Preprocessor, Compiler, Assembler, Linker;

function run() {
 $this->preprocess();
 $this->compile();
 $this->createObjCode();
 $this->createExec();

  echo 'Execute the file...done' . '<br/>';
 }
}
$ide = new IDE();
$ide->run();
  1. 组合多个特征

通过在特征声明中使用 use 语句,特征可以由其他特征组成。请参阅以下示例:

<?php

trait Reader{
public function read($source){
   echo sprintf("Read from %s <br/>",$source);
  }
}

trait Writer{
public function write($destination){
   echo sprintf("Write to %s <br/>",$destination);
  }
}

trait Copier{
use Reader, Writer;
public function copy($source,$destination){
   $this->read($source);
   $this->write($destination);
 }
}

class FileUtil{
use Copier;
public function copyFile($source,$destination){
   $this->copy($source, $destination);
 }
}

关于php trait 使用另一个 trait,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20745907/

相关文章:

php - 在带有列名的关联数组中循环

php - 我想使用 Ajax 将 id 从 View 传递到 Codeigniter 中的 Controller 并更新数据库中的下拉选择

c++ - 在类中不定义静态数组大小是不是很糟糕?--而是让它自动调整大小

c++ - 如何使用重载运算符合并两个数组?

java - 在java中比较一个大列表与另一个小列表的最佳方法?

c++ - 在列表中调用子对象

php - 以前的文件值也被附加到在 php 中一一写入的 xml 文件中

php - Laravel 5.5 获取最近更新的多条记录

Python - 迭代扩展类的类列表?

php - PHP 是否有用于 print_r 或 var_dump 的接口(interface)?