简体   繁体   中英

Public functions vs Functions in CodeIgniter

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?

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.

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 (eg 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.

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.

  • Both declarations are same and both functions will be available by URI request in codeigniter
  • To prevent a method from being called by user use private or protected access specifiers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM