Home  >  Article  >  Backend Development  >  How to create a class and call it in php?

How to create a class and call it in php?

silencement
silencementOriginal
2019-09-24 18:04:124323browse

How to create a class and call it in php?

PHP class definition

The usual syntax format for PHP definition classes is as follows:

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

The analysis is as follows:

Classes use the class keyword Add the class name definition after.

Variables and methods can be defined within a pair of braces ({}) after the class name.

Variables of the class are declared using var, and variables can also be initialized.

Function definition is similar to the definition of PHP function, but the function can only be accessed through the class and its instantiated objects.

For example

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

The variable $this represents its own object.

PHP_EOL is the newline character.

Creating objects in PHP

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;

In the above code, we created three objects, Each of the three objects is independent. Next, let's take a look at how to access member methods and member variables.

Call member methods

After instantiating an object, we can use the object to call member methods. The member methods of the object can only operate the member variables of the object:

// 调用成员函数,设置标题和URL
$runoob->setTitle( "菜鸟教程" );
$taobao->setTitle( "淘宝" );
$google->setTitle( "Google 搜索" );

$runoob->setUrl( &#39;www.runoob.com&#39; );
$taobao->setUrl( &#39;www.taobao.com&#39; );
$google->setUrl( &#39;www.google.com&#39; );

// 调用成员函数,获取标题和URL
$runoob->getTitle();
$taobao->getTitle();
$google->getTitle();

$runoob->getUrl();
$taobao->getUrl();
$google->getUrl();

The above is the detailed content of How to create a class and call it 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