In PHP, What is the difference between declaring methods inside class like
public function
VS function
For example:
public function contact()
{
$data['header'] = "Contact";
$this->load->view('admin/admin_contact', $data);
}
VS
function contact()
{
$data['header'] = "Contact";
$this->load->view('admin/admin_contact', $data);
}
Is it better practice to use public function or function and why?
Methods declared with any explicit visibility keyword is best practice. It looks and feels better and it doesn't confuse people.
- Most PHP5 coding conventions (e.g. Zend, Symfony...) require the public keyword, so it's familiar.
- It means that variable and method declarations use the same syntax.
- It's more explicit and forces developers to consider their method
visibility.
According to PHP.net
Class methods may be defined as public, private, or protected. Methods declared without any explicit visibility keyword are defined as public.
for best practice, i suggest using visibility keywords (esp when using higher versions of PHP). it prevents confusion (like the one you are in now) and promotes standard practice in coding.
There is no difference between these two.
Both are the same.
In codeigniter both have same meaning
and can be called by using standard URI tags unless you give a '_' in front of your function name
_fname()
will not be called
They are the same thing .... if you do not specify the visibility methods / functions are declared as public
Methods declared without any explicit visibility keyword are defined as public
from the docs here
If you really want best practice you will always use public. But for the codeigniter Framework it doesn't mather if you declare it public or not. Note that if you want a controller to be private you dont use private but you will use the underscore (_) in front of your controller name so it wont be visible.