PHP object-oriented: member methods, member variables, class constants

巴扎黑
Release: 2023-03-07 11:08:01
Original
7809 people have browsed it

Member method

Before we talked about the php class definition and instantiation method, we gave an example and created a Human kind.

But people not only have attributes, but also behaviors. For example, people can run, dance, sing, eat, etc. So, how do we implement these behaviors? Next we will use our member methods to implement it.

Still the example from the previous lesson, define a human class and create a running member method

class Preson{
     public $name;
     public $age;
     public $gender;
     public function Run(){           //声明成员方法
                   echo "人在塔在";
              }
}
//先实例化一个类
$Preson1 = new Preson();
$Preson1->name = "德玛西亚";
//调用成员方法
$Preson1->Run();
Copy after login

This example is a simple member method creation call.

Member variables

Variables in the class are also called member variables. We have already used them in our previous examples. Here they are proposed to you. Explain.

class Preson{
   public $name;              //定义成员变量
   public $age;
}
Copy after login

$name in the above example is a member variable.

Class constants

If there are variables in the class, then there will be constants. A constant means a quantity that does not change, a constant value.

To define constants, we use const.

<?php
class  character{
public $name;                     //声明一个变量
const SKILLS = &#39;哈撒尅&#39;;  //声明一个常量
}
$character1 = new character();
$character1->name = "亚索";
echo &#39;我要玩&#39; . $character1->name . &#39;<br/>&#39; . &#39;技能是&#39; . character::SKILLS;
Copy after login

The above example shows how to define and access constants.

The above is the detailed content of PHP object-oriented: member methods, member variables, class constants. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!