What are the uses of php classes and objects

silencement
Release: 2023-02-25 12:12:01
Original
2737 people have browsed it

What are the uses of php classes and objects

A class is a collection of objects that have the same properties and methods. Objects are instantiations of classes. Creating a class is very simple. Just use the class keyword plus curly brackets, as follows

<?php
class Person
{
    
}
Copy after login

as above. In this way, a class named Person is created. Usually, the first letter of the class name needs to be capitalized. of.

To instantiate an object, you need to use the new keyword. Below we instantiate an object and name it $p1

<?php
class Person
{

}
$p1 = new Person();
Copy after login

In this way, an instance is created. Of course, this class There are no member variables (that is, attributes) and member methods (that is, functions). We can also add some attributes and methods to this class

<?php
class Person
{
    var $name;
    var $sex;
    var $age;
    function say(){
        echo"这个人在说话";
    }

    function run(){
        echo "这个人在走路";
    }
}
$p1 = new Person();
$p2 = new Person();
$p3 = new Person();
Copy after login

Now we will use this class to create three instance objects, namely $p1, $p2, $p3. The advantage of using classes is that objects can be instantiated quickly. With objects, we can implement some methods and functions.

The above is the detailed content of What are the uses of php classes and objects. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template