Public functions vs Functions in CodeIgniter

我的未来我决定 提交于 2019-12-06 16:44:40

问题


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?


回答1:


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.



回答2:


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.




回答3:


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




回答4:


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




回答5:


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.




回答6:


  • 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.


来源:https://stackoverflow.com/questions/9849984/public-functions-vs-functions-in-codeigniter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!