How to define a class in php

silencement
Release: 2023-02-25 07:48:02
Original
3946 people have browsed it

How to define a class in php

PHP class definition

The usual syntax format of PHP definition class is as follows:

<?php
class phpClass {
  var $var1;
  var $var2 = "constant string";
  
  function myfunc ($arg1, $arg2) {
     [..]
  }
  [..]
}
?>
Copy after login

The analysis is as follows:

类使用 class 关键字后加上类名定义。
类名后的一对大括号({})内可以定义变量和方法。
类的变量使用 var 来声明, 变量也可以初始化值。
函数定义类似 PHP 函数的定义,但函数只能通过该类及其实例化的对象访问。
Copy after login

Example

<?php
class Site {
  /* 成员变量 */
  var $url;
  var $title;  
  /* 成员函数 */
  function setUrl($par){
     $this->url = $par;
  }
  function getUrl(){
     echo $this->url . PHP_EOL;
  } 
  function setTitle($par){
     $this->title = $par;
  }  
  function getTitle(){
     echo $this->title . PHP_EOL;
  }
}
?>
Copy after login

After the class is created, we can use the new operator to instantiate objects of this class:

$runoob = new Site;
$taobao = new Site;
$google = new Site;
Copy after login

The above is the detailed content of How to define a class in php. 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