When to use a Class vs. Function in PHP

后端 未结 6 1955
长发绾君心
长发绾君心 2020-12-02 08:59

The lightbulb has yet to go on for this...

I\'d really love an easy to understand explanation of the advantage to using a class in php over just using functions. <

6条回答
  •  粉色の甜心
    2020-12-02 09:28

    I have a list of places you would use OOP-Style Classes in my answer to this question: https://stackoverflow.com/questions/2035449/why-is-oop-hard-for-me/2035482#2035482

    Basically, whenever you want to represent an object that has things in it. Like a database variable that has a connection in it that is unique. So I would store that so I can make sure that the mysql_query uses the correct connection everytime:

    class MySQL extends Database
    {
        public function connect($host, $user, $pass, $database)
        {        
            $this->connection = mysql_connect($host, $user, $pass);
            $this->select_db($database);
        }
    
        public function query($query)
        {
            return mysql_query($query, $this->connection);
        }
    
        public function select_db($database)
        {
            mysql_select_db($database);
        }    
    }
    

    Or maybe you want to build a Form, you could make a form object that contains a list of inputs and such that you want to be inside the form when you decide to display it:

    class Form
    {
        protected $inputs = array();
        public function makeInput($type, $name)
        {
             echo '';
        }
    
        public function addInput($type, $name)
        {
             $this->inputs[] = array("type" => $type,
                    "name" => $name);
        }
    
        public function run()
       {
           foreach($this->inputs as $array)
           { 
              $this->makeInput($array['type'], $array['name'];
           }
        }
    }
    
    $form = new form();
    
    $this->addInput("text", "username");
    $this->addInput("text", "password");
    

    Or as someone else suggested, a person:

    class Person{
    
        public $name;
        public $job_title;
        // ... etc....
    
    }
    

    All are reasons to create classes as they represent something that has properties like a name or a job title, and may have methods, such as displaying a form.

提交回复
热议问题