面向对象的php对象,类和方法

时间:2013-12-09 05:41:15

标签: php oop object

$Clint_ip=$this->request->clintIp();

我可以得到关于这一行的清晰概念吗?在这里我知道$ clint_ip是一个变量,但接下来的三个是什么?哪一个是对象? 哪一种方法? 哪一个是班级?

我只需要理解这一行。在几个项目中我看过这种类型的行。在这一行中哪一个叫做对象?如果你想要你可以给另一个例子。在这里$ this是一个对象?还是类?或方法?

3 个答案:

答案 0 :(得分:2)

$Clint_ip是一个变量,

  1. 与其他基于面向对象的编程语言一样,$this是包含它的类的this。 (有关此When to use self over $this?
  2. 的更多信息
  3. request看起来像是另一个类的对象
  4. clintIp()public对象类的request方法

答案 1 :(得分:1)

您提供的代码似乎来自班级内部。


一个类表示如下:

class Example {
    private $foo;
    public $bar;

    public function __construct() {

    }

    public function method() {

    }

    private function other() {

    }
}

创建此类的对象时,可以使用以下格式:

$example = new Example();

这会调用构造函数__construct()

创建(“实例化”)此对象后,您可以使用 - >调用对象的属性。

所以,我可以说

$example->bar = "Foo"; 

将此属性设置为字符串。


您的代码

在您的代码中,属性“request”本身就是一个对象(类的实例)。

$Clint_ip=$this->request->clintIp();

以下是可以使用的代码示例

class Example {
    public $request;

    public function __construct($request) {
        $this->request = $request;
    }

}

class Request {
    public function clintIp() {
        //return something
    }
}

然后是一些背景:

$request = new Request;
$example = new Example($request);

$clint_ip = $example->request->clintIp();

所以在这里,$clint_ip是变量。 $example$request是对象(类的实例),clintIp()是请求对象的方法。

现在,关于“$ this”。这表明它在对象“Example”中:

想象一下,类Example现在有一个方法

public function test() {
    return $this->request->clintIp();
}

$this表示它位于对象的实例内部。在static上下文中,使用“self ::”,如其他答案中所述。

答案 2 :(得分:0)

您是具有请求属性的对象内部。 Request属性包含带有方法clintIp()的对象,它返回客户端ip。

相关问题