Home  >  Article  >  Backend Development  >  How to define a class in php

How to define a class in php

silencement
silencementOriginal
2019-09-26 17:10:193914browse

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) {
     [..]
  }
  [..]
}
?>

The analysis is as follows:

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

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;
  }
}
?>

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;

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!

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