本文介紹了在php中沒有對象實(shí)例化的情況下調(diào)用類方法(帶構(gòu)造函數(shù))的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
限時送ChatGPT賬號..
我已經(jīng)查看并嘗試過,但我找不到答案.
Ive looked and tried but I can't find an answer.
在 PHP 中,是否可以在不將其實(shí)例化為對象的情況下調(diào)用類的成員函數(shù)(當(dāng)該類需要構(gòu)造函數(shù)來接收參數(shù)時)?
In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object?
代碼示例(給出錯誤):
A code example (which gives errors):
<?php
class Test {
private $end="";
function __construct($value) {
$this->end=$value;
}
public function alert($value) {
echo $value." ".$this->end;
}
}
//this works:
$example=new Test("world");
$example->alert("hello");
//this does not work:
echo Test("world")::alert("hello");
?>
推薦答案
不幸的是 PHP 不支持這樣做,但你是一個有創(chuàng)造力和外觀的人 :D
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D
您可以使用工廠",示例:
You can use an "factory", sample:
<?php
class Foo
{
private $__aaa = null;
public function __construct($aaa)
{
$this->__aaa = $aaa;
}
public static function factory($aaa)
{
return new Foo($aaa);
}
public function doX()
{
return $this->__aaa * 2;
}
}
Foo::factory(10)->doX(); // outputs 20
這篇關(guān)于在php中沒有對象實(shí)例化的情況下調(diào)用類方法(帶構(gòu)造函數(shù))的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!
【網(wǎng)站聲明】本站部分內(nèi)容來源于互聯(lián)網(wǎng),旨在幫助大家更快的解決問題,如果有圖片或者內(nèi)容侵犯了您的權(quán)益,請聯(lián)系我們刪除處理,感謝您的支持!