需要帮助解释这个 - >或 - >在PHP中

时间:2016-06-03 06:13:24

标签: php html

有人可以解释我$this->->以及整个公共函数__construct

这是我的代码

<?php
class Person {



 public function __construct($firstname, $lastname, $age) {
     $this->firstname = $firstname;
     $this->lastname = $lastname;
     $this->age = $age;
 }
public function greet(){
    return "Hello, my name is" . $this->firstname . " " .$this->lastname .     "Nice to meet you ! :-)";
    }
}
$teacher = new Person ("boring", "12345", 12345);
$student = new Person("Mihail", "Dimitrovski", 1995);
 echo $student->age;
echo $teacher->greet();
?>

3 个答案:

答案 0 :(得分:1)

一个类是蓝图。当您创建这样的类时,例如:

class Person
{
    function __construct($firstName, $lastName, $age)
    {

    }

    $firstName;
    $lastName;
    $age;
}

你实际上是在描述一个人是什么。该类的每个实例,每个人都将包含这3个属性(名字,姓氏和年龄)。

如果您实例化这样的新人:

$student = new Person("Mihail", "Dimitrovski", 1995);

您可以使用->运算符访问这3个属性:

echo $student->firstName;
echo $student->lastName;
echo $student->age;

当您想要从对象本身访问这些属性时,您会执行相同的操作。因此,如果您的Person类中有一个函数,则打印全名:

function fullName()
{
    echo $this->firstName . ' ' . $this->lastName;
}

您需要一种方法来引用这些属性,但由于您还没有实例,因此您使用$this来表示您正在引用当前实例

答案 1 :(得分:0)

$这 - &GT;用于访问类中类的属性或方法,而$ person-&gt;当你想要访问类外的类的方法和变量时,将使用它。

答案 2 :(得分:0)

如果您想要访问对象内部的属性或方法,则每次都使用->调用它。

例如,$student->age调用学生的年龄属性。

在Java中,它看起来像这样:student.age。它只是一种调用对象的方法和属性的方法。

如果您致电$this->firstname,请拨打目前正在编码的班级的属性。

例如:

class Person
{
    public $name;

    public function __construct($someString, $someString2, $number)
    {
        // Write your code here.
    }

    public function greet()
    {
        echo "Hey, my name is " . $this->name.
    }
}

每次启动对象的新实例时都会调用__construct方法,即:

$studen = new Person("boring", "12345", 12345);
相关问题