Home  >  Article  >  Backend Development  >  Simple example of php object-oriented

Simple example of php object-oriented

WBOY
WBOYOriginal
2016-07-25 09:00:18840browse
Let me introduce to you a simple example of PHP object-oriented. Friends in need can refer to it.

The following is an example of PHP object-oriented object. It is very simple and helps everyone master the idea of ​​PHP oop.

1. Define the class

<?php
    //定义一个类
    //bbs.it-home.org
    /*
    class Cat{
    
            public $name;
            public $age;
    }

    $cat1=new Cat();
    $cat1->name ="小白";
    $cat1->age=10;
    echo $cat1->name.'---'.$cat1->age;
*/
    //对象传递的形式,地址传递
    class Person{
        
        public $name;
        public $age;
    }

    //定义一个方法,接收对象,并改变对象的name
    function changeNane($obj){   
        $obj->name="我已经改名为:张三。";
    }

    //创建一个对象
    $a = new Person;
    $a->name="小明";
    $a->age=21;
    $b=$a; 
    //调用方法
    changeNane($a);
    //输出$a,$b
    echo '$a是:'.$a->name.'<br/>';
    echo '$b是:'.$b->name;
    //从输出结果来看,对象的赋值或者函数接收对象时都是地址传递,他们指向同一地址
?>

Summary: 1. Class is abstract and represents a type of thing 2. The object is concrete, a specific instance of the class, or the class is the template of the object, and the object is an individual instance of the class. 3. Member attributes, which can be basic data types (integers, decimals, characters, Boolean) or composite data types (arrays, objects) 4. If a file is specifically used to define a class, the naming convention should be like classname.class.php 5. When assigning an object or when a function receives an object, the address is passed. They point to the same address



Statement:
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