说我有以下课程:
class App {
public static $url;
static function boot () {
self::$url = new Url();
}
}
class Url {
function redirect ($url) {
header('Location: '.$url);
}
}
我如何使用这个类:
App::boot();
$app = App;
$app->url->redirect('http://example.com');
???
答案 0 :(得分:3)
你有什么理由想让你的班级App
成为静态的吗?
否则,您可以这样做:
class App {
public $url;
public function __construct(){
$this->url = new Url();
}
}
class Url {
function redirect ($url) {
header('Location: '.$url);
}
}
$app = new App();
$app->url->redirect('http://example.com');
如果你想让它保持静止:
class App {
public static $url;
public static function boot(){
self::$url = new Url();
}
}
class Url {
function redirect ($url) {
header('Location: '.$url);
}
}
App::boot();
App::$url->redirect('http://example.com');
答案 1 :(得分:0)
您可以使用变量访问静态属性(请参阅下面的代码),但我建议您避免使用它。
class App {
public static $url;
public static function boot(){
self::$url = new Url();
}
}
class Url {
function redirect ($url) {
header('Location: '.$url);
}
}
$app = 'App';
$app::$url->redirect('http://example.com');