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( 'www.runoob.com' ); $taobao->setUrl( 'www.taobao.com' ); $google->setUrl( 'www.google.com' ); // 调用成员函数,获取标题和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!