douzhen9428 2010-11-14 05:08
浏览 80
已采纳

PHP对象/类

Hey, I'm learning PHP, and i cant get my head around PHP classes/objects. I understand JavaScript Objects/Classes, but i cant seem to grasp PHP. What i mainly want it for is so i can do this sort of thing. (note this might cross JS and PHP)

$SQL = $db->query("SELECT *
                   FROM table
                   WHERE 1 = ");

$table_assoc = $db->assoc_array($SQL);
$table_array = $db->num_array($SQL);

Ive seen this type of thing done in PHP frameworks, but how does it all work? Thanks in advance!

  • 写回答

3条回答 默认 最新

  • douxishai8552 2010-11-14 05:17
    关注

    If you want to design a class for database access, I'd suggest you don't. There are already many classes that do just that. There is a PHP extension called PDO that can help you do the type of thing above and it is already well tested. Here is a link to good tutorial on it: http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html

    OOP in PHP is very similar to OOP in other languages such as C++, C# (similar not the same, the basic concepts are very transferable. You should probably look into the links posted above to understand that in detail).

    Edit

    Let's see how this goes :). Here are the basics.

    A class is a type of something. You can have a Person class, Car class etc.

    An object is an instance of the class. It is one thing of that type. In a PHP context, this is how this will look:

    class Person // Class
    {
       public $name; // Property
    
       public function setName($n) // Method
       {
           $this->name = $n;
       }
    }
    

    I have created a class called Person.

    $p = new Person(); // An instance of Person class
    

    I have created an instance of the class. $p is an object of type Person.

    The $name inside is a member variable(/attribute). Think of it is as one of the properties that defines a Person. The Person class is a container for a set of data that defines a Person; name is one just one such data.

    A class can have methods. Think of these as ways you interact with the class. You can call a method for the class to do something. In the above example, the setName method can be called with 1 argument. This argument is set as the value of the name member variable. The $this has to be used to refer to member variables (the $n is not a member variable, i.e. it is not a property of the class)

    This should give you the basics to get started. Everything else builds on this.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?