Problem
I’ve been trying to find out how to do this but can’t seem to figure it out.
Here’s an example of what I’m attempting:
class test {
public newTest(){
function bigTest(){
//Big Test Here
}
function smallTest(){
//Small Test Here
}
}
public scoreTest(){
//Scoring code here;
}
}
This is where I’m having trouble: how can I call bigTest()?
Asked by WAC0020
Solution #1
Try this one:
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();
Answered by Sergey Kuznetsov
Solution #2
The example you gave is invalid PHP and contains the following flaws:
public scoreTest() {
...
}
is not a valid function declaration; functions must be declared using the ‘function’ keyword.
Instead, the syntax should be:
public function scoreTest() {
...
}
Second, enclosing the bigTest() and smallTest() routines in a public function() does not make them private; you must put the private keyword on each of these functions separately:
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;
}
}
In class declarations, it is also customary to capitalize class names (‘Test’).
Hope that helps.
Answered by pjbeardsley
Solution #3
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;
}
}
Answered by Meganathan S
Solution #4
I believe you’re looking for something similar to this.
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();
Answered by Ali Hasan
Solution #5
You must “point” to any method of an object instantiated from a class (with statement new) in order to call it. You simply use the resource produced by the new statement from the outside. PHP stores the same resource into the $this variable inside any object created by new. As a result, you must use $this to point to the method within a class. To call smallTest from within your class, you must tell PHP which of the objects created by the new statement you want to run, simply write:
$this->smallTest();
Answered by Ingeniero
Post is based on https://stackoverflow.com/questions/1725165/calling-a-function-within-a-class-method