PHP |对象

对象 是由类定义的数据结构的单个实例。我们定义一个类,然后创建许多属于它的对象。对象也称为实例。

null

创建对象: 下面是一个如何使用创建对象的示例 操作人员

class Books {
   // Members of class Books
}

// Creating three objects of Books
$physics = new Books;
$maths = new Books;
$chemistry = new Books;

成员职能: 创建对象后,我们可以调用与该对象相关的成员函数。成员函数通常只访问当前对象的成员。

例子:

$physics->setTitle( "Physics for High School" );
$chemistry->setTitle( "Advanced Chemistry" );
$maths->setTitle( "Algebra" );

$physics->setPrice( 10 );
$chemistry->setPrice( 15 );
$maths->setPrice( 7 );

以下语法用于以下示例中详述的以下程序:

例子:

<?php
class Books {
/* Member variables */
var $price ;
var $title ;
/* Member functions */
function setPrice( $par ){
$this ->price = $par ;
}
function getPrice(){
echo $this ->price. "<br>" ;
}
function setTitle( $par ){
$this ->title = $par ;
}
function getTitle(){
echo $this ->title. "<br>" ;
}
}
/* Creating New object using "new" operator */
$maths = new Books;
/* Setting title and prices for the object */
$maths ->setTitle( "Algebra" );
$maths ->setPrice( 7 );
/* Calling Member Functions */
$maths ->getTitle();
$maths ->getPrice();
?>


施工人员: 构造函数是PHP面向对象编程中的一个关键概念。PHP中的构造函数是一个类的特殊类型的函数,当该类的任何对象被创建或实例化时,它会自动执行。 构造函数也称为magic function,因为在PHP中,magic方法通常以两个下划线字符开头。

下面是构造函数实现的示例代码: 施工人员计划:

<?php
class GeeksforGeeks
{
public $Geek_name = "GeeksforGeeks" ;
// Constructor is being implemented.
public function __construct( $Geek_name )
{
$this ->Geek_name = $Geek_name ;
}
}
// now constructor is called automatically
// because we have initialized the object
// or class Bird.
$Geek = new GeeksforGeeks( "GeeksforGeeks" );
echo $Geek ->Geek_name;
?>


输出:

GeeksforGeeks
© 版权声明
THE END
喜欢就支持一下吧
点赞7 分享