在我的php项目中,我创建了4个类
CONNECTION
class Mysqliconn {
public $mysqli;
public function __construct(){
include "dbconfig.php";
$this->connect($host, $user, $password, $database, $charset);
}
public function connect (.....)
$this->mysqli = new mysqli(......);
}
}
UPLOAD
class Upload {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getID($id) {
echo $id;
}
}
USERS
class Users {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getName($name) {
echo $name;
}
}
CARS
class Cars {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getCars($cars) {
echo $cars;
}
}
在我的php页面中,我以这种方式实例化了
function __autoload($class_name) {
if(file_exists('class/class.' . strtolower($class_name) . '.php')) {
require_once('class/class.' . strtolower($class_name) . '.php');
}
else {
throw new Exception("Unable to load $class_name.");
}
}
$db = new Mysqliconn();
$up = new Upload($db);
$us = new Users($db);
$cs = new Cars($db);
$cs->getCars('BMW');
$us->getName('Foo');
在我的汽车类中,我想调用用户和上传类的方法。 有可能做到吗?我怎么能这样做?谢谢。
答案 0 :(得分:2)
class Example{
public function __construct(){
$otherClass = new OtherClass();
$otherClass->functionInOtherClass();
}
}
或
class Example{
public function __construct($objFromOtherClass){
$objFromOtherClass->functionInOtherClass();
}
}
或
class Example{
public function __construct(OtherClass $objFromOtherClass){
$objFromOtherClass->functionInOtherClass();
}
}
如果有问题的对象将在Example
课程中使用:
class Example{
protected $objFromOtherClass;
public function __construct(OtherClass $objFromOtherClass){
$this->objFromOtherClass = $objFromOtherClass;
}
public function test(){
$this->objFromOtherClass->functionInOtherClass();
}
}
答案 1 :(得分:1)
您可以在其他类中调用公共静态函数:
class Users {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public static function getName($name) {
echo $name;
}
}
class Cars {
private $db;
public function __construct( Mysqliconn $db ) {
$this->db = $db;
}
public function getCars($cars) {
echo $cars;
}
public function callGetName($name)
{
return Users:: getName($name) ;
}
}
另一种选择是:
function callGetName($name)
{
$user = new Users();
$user->getName($name);
}