WAC*_*020 101 php methods class function call
我一直试图弄清楚如何去做,但我不太确定如何.
这是我想要做的一个例子:
class test {
public newTest(){
function bigTest(){
//Big Test Here
}
function smallTest(){
//Small Test Here
}
}
public scoreTest(){
//Scoring code here;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我遇到问题的部分,如何调用bigTest()?
Ser*_*sov 195
试试这个:
class test {
public function newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
$testObject = new test();
$testObject->newTest();
$testObject->scoreTest();
Run Code Online (Sandbox Code Playgroud)
pjb*_*ley 20
您提供的示例不是有效的PHP,并且存在一些问题:
public scoreTest() {
...
}
Run Code Online (Sandbox Code Playgroud)
不是一个正确的函数声明 - 您需要使用'function'关键字声明函数.
语法应该是:
public function scoreTest() {
...
}
Run Code Online (Sandbox Code Playgroud)
其次,将publicTest()和smallTest()函数包装在public function(){}中并不会使它们变为私有 - 您应该在这两个函数上单独使用private关键字:
class test () {
public function newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public function scoreTest(){
//Scoring code here;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,通常在类声明('Test')中大写类名.
希望有所帮助.
我想你正在寻找像这样的东西.
class test {
private $str = NULL;
public function newTest(){
$this->str .= 'function "newTest" called, ';
return $this;
}
public function bigTest(){
return $this->str . ' function "bigTest" called,';
}
public function smallTest(){
return $this->str . ' function "smallTest" called,';
}
public function scoreTest(){
return $this->str . ' function "scoreTest" called,';
}
}
$test = new test;
echo $test->newTest()->bigTest();
Run Code Online (Sandbox Code Playgroud)
小智 8
class test {
public newTest(){
$this->bigTest();
$this->smallTest();
}
private function bigTest(){
//Big Test Here
}
private function smallTest(){
//Small Test Here
}
public scoreTest(){
//Scoring code here;
}
}
Run Code Online (Sandbox Code Playgroud)
小智 5
要调用从类实例化的对象的任何方法(使用语句 new),您需要“指向”它。从外部,您只需使用由 new 语句创建的资源。在由 new 创建的任何对象 PHP 中,将相同的资源保存到 $this 变量中。因此,在类中,您必须通过 $this 指向该方法。在您的类中,smallTest要从类内部调用,您必须告诉 PHP 您要执行 new 语句创建的所有对象中的哪一个,只需编写:
$this->smallTest();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
337429 次 |
| 最近记录: |