php trait使用另一个特性

The*_*uls 9 php oop class traits

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

settings.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());}
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

为database.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());}
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

users.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
    }
}
?>
Run Code Online (Sandbox Code Playgroud)

现在我收到了这个错误:

致命错误:在第18行的/home/deb2371/domains/nonamenohistory.com/public_html/include/classes/class.database.php中调用未定义的方法users :: readSetting()

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

如果是这种情况,我不会得到任何错误,但遗憾的是情况并非如此.

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

小智 16

也许是因为readSetting实际上叫做getSetting?

  • ouch ...你是对的。我从其他班级复制了它,却忘了更改它。我很想念我,这太愚蠢了。谢谢。 (3认同)

Moh*_*lal 14

代码重用是面向对象编程最重要的方面之一.

一个简单的例子Multiple Traits,并Composing 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();
Run Code Online (Sandbox Code Playgroud)
  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);
 }
}
Run Code Online (Sandbox Code Playgroud)

  • 显然,考虑到这个问题的通用标题,这个答案对于 99% 的访问者来说都是正确的。感谢您提供详细的示例!(就我而言,我只是因为我自己的“语法错误”而来到这里,但你的示例澄清了我的特征配置正确,并且我发现了问题,正如预测的那样) (2认同)