homepage Welcome to WebmasterWorld Guest from 54.161.240.10
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Pubcon Platinum Sponsor 2014
Visit PubCon.com
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

    
PHP calling function within a class.
jigney




msg:4676061
 12:41 pm on May 30, 2014 (gmt 0)

Here is the code what i do, To call a function within a class,
Which works fine, But i want to know that is there any other way to Call function within a class?
class demo {
public function demo_one(){
$this->demo_big();
$this->demo_small();
}

private function demo_big(){
// Code for demo_big
}

private function demo_small(){
// Code for demo_small
}

public function demo_test(){
// Code for demo_test
}
}

$demoObject = new demo();

$demoObject->demo_one();

$demoObject->demo_test();

 

coopster




msg:4676064
 1:02 pm on May 30, 2014 (gmt 0)

You are trying to call a private function (method) from outside the parent class itself and that will throw a FATAL ERROR. If you truly need the ability to call that function from the "outside" then you can merely change it to a public function. More reading here:
[php.net...]

derfmann




msg:4676265
 6:19 am on May 31, 2014 (gmt 0)

hmmh ... it works or. so you want just know if there are other ways to achieve the same?

1. static methods

public function demo_one(){
// $this->demo_big();
// $this->demo_small();

self::demo_small();
self::demo_big();
}

private static function demo_big(){
echo 'demo_big';
}

private static function demo_small(){
echo 'demo_small';
}


2. call_user_func

public function demo_one(){
// $this->demo_big();
// $this->demo_small();

$methodsToCall = array('demo_big', 'demo_small');
foreach($methodsToCall as $methodName) {
if (method_exists($this, $methodName)) {
call_user_func(array($this, $methodName));
}
}
}

jigney




msg:4677894
 8:01 am on Jun 6, 2014 (gmt 0)

Thanks for your suggestion, Will try it...

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved