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! 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. 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. 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. Link to comment https://forums.phpfreaks.com/topic/261873-oop-php-functions/#findComment-1341874 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.