Bryce910 Posted May 1, 2012 Share Posted May 1, 2012 When in OOP I have been watching tutorials and some have functions just written like class user { public $user; public function __construct($u) { $this->user = $u; } } do I need to type public before the function or is it better practice to just put class user { public $user; function __construct($u) { $this->user = $u; } } Thanks! Quote Link to comment https://forums.phpfreaks.com/topic/261873-oop-php-functions/ Share on other sites More sharing options...
mlj0102 Posted May 1, 2012 Share Posted May 1, 2012 I believe all functions are public unless nested and you should declare the type of function public or private. Quote Link to comment https://forums.phpfreaks.com/topic/261873-oop-php-functions/#findComment-1341825 Share on other sites More sharing options...
marcus Posted May 1, 2012 Share Posted May 1, 2012 Functions are public without any cast. class A { public $user; public function __construct(){ $this->user = 'apple'; } function getApple(){ return $this->user; } } class B { public $user; public function __construct(){ $a = new A(); $this->user = 'b' . $a->getApple(); } function getApple(){ return $this->user; } } $b = new B; echo $b->getApple(); This code would return bapple. If the getApple() method in A was private, B would not be able to access A's getApple() method. However, if A's getApple() method was protected, and class B extends A, then you would be able to access A's getApple() method. Quote Link to comment https://forums.phpfreaks.com/topic/261873-oop-php-functions/#findComment-1341833 Share on other sites More sharing options...
ignace Posted May 1, 2012 Share Posted May 1, 2012 It's better to write public. Quote Link to comment https://forums.phpfreaks.com/topic/261873-oop-php-functions/#findComment-1341874 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.