How to create a class and call it in php?

silencement
Release: 2023-02-24 19:18:01
Original
4359 people have browsed it

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

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;
  }}?>
Copy after login

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;
Copy after login

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();
Copy after login

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!

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