【问题标题】:With or without $this in PHP [duplicate]PHP中有或没有$this [重复]
【发布时间】:2019-05-12 13:31:15
【问题描述】:

我是 OOP PHP 新手。为什么我们必须使用$this 引用,而代码在没有它的情况下也可以工作?

如果我从这个代码片段中同时删除$this(在->sql 之前),那么修改也是有效的。虽然我读过它,但我仍然不明白给定方法中的$this 是什么。

class blogs{

    private $servername = "localhost";
    private $username = "root";
    private $password = "";
    private $dbname = "asd";
    private $conn = "";
    private $result = "";
    private $row = "";
    private $sql = "";

    public function cmd_update(){
        $this->sql = "UPDATE 
                blogs 
                SET
                `name` = '".$_GET['input_name']."',
                `date` = '".date('Y-m-d H:m:s')."',
                WHERE
                id = ".$_GET['input_modifying_id']."        
        ";

        if ($this->conn->query($this->sql) === TRUE) {
            echo "Successfully modified!";
        } else {
            echo "Modifying Unsuccessful!";
        }       
    }

【问题讨论】:

  • $this 用于引用您所在的类。如果您使用$this->foo = 'bar';,则可以从其他方法访问$this->foo(如果设置为,则从类外部访问) public),而没有 $this 的变量将是一个局部变量,只能在该特定方法的范围内访问。所以$this->foo$foo是不同作用域的两个不同变量。
  • $this 是该类的当前实例。例如,如果您有多个 Blog 实例,则每个实例都可以有自己的 $this->title,不会干扰 其他 Blog 实例。
  • 通过删除$this->sql 前面的$this,您将把它变成一个私有作用域的变量,该变量不能在类中访问(在cmd_update 之外)。通过指定$this->sql,您将其分配给成员变量。
  • 旁注:看到您似乎是一个新的编码员,您的代码对 SQL 注入是开放的。最好使用准备好的声明。您不希望您的数据库有一天被破坏或删除。

标签: php oop this


【解决方案1】:

$this 指的是当前对象 - 在这种情况下,$thisblogs 类的简写。

让我们以这个类为例:

class Foo
{
    protected $a;

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

    public function getA()
    {
        return $this->a;
    }
}

在这里,我只是将 $a 分配给传递给新 Foo 实例的任何内容,并创建一个公共可访问的函数来返回 $a。

我们使用 $this 来指代我们当前所在的位置,$this->aprotected $a

这对开发人员来说是一个非常方便的功能,因为这意味着我们不必创建自己的方式来获取实例而无需重新声明。这也意味着我们可以使用模板更容易使用。例如

class Foo
{
    public function sayHi()
    {
        return 'hello world';
    }
}

class Bar extends Foo
{}

因为 public 函数很好.. public 我们可以使用 $this 访问父类:

<?php
    $bar = new Bar();
    echo $bar->sayHi(); # will output hello world

这也意味着我们可以创建一组与对象相关的通用函数和属性,以允许更多动态代码。阅读这些博客:

title = hello world
content = hello world
img = /path/to/img.jpg

title = what we did last summer
content = played in the park
img = /path/to/another/img.jpg

我们可以有一个这样的博客类:

class GenericController
{
    # pretend we've done some PDO set up here where we set new PDO to $this->pdo
    public function load($id)
    {
        $sql = 'SELECT * FROM `blogs` WHERE `id` = :id';
        $res = $this->pdo->prepare($sql);
        $res->execute(array(':id' => $id));

        return (object) $res->fetch(PDO::FETCH_ASSOC);
    }
}

class Blog extends GenericController
{
    protected $id;
    protected $data;

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

    protected function loadData()
    {
        $this->data = $this->load($this->id);
    }

    public function getTitle()
    {
        return $this->data->title;
    }

    public function getContent()
    {
        return $this->data->content;
    }

    public function getImg()
    {
        return $this->data->img
    }
}

$blogOne = new Blog(1);
$blogTwo = new Blog(2);

echo $blogOne->getTitle(); # will output hello world
echo $blogTwo->getTitle(); # will output what we did last summer

进一步阅读:

由于 MySQL 注入原因(您的代码目前对所述注入开放):

PDO
PDO Prepared Statements

对于 OOP:

The Basics
Visibility

还有来自文档本身的$this(可以通过基础链接找到):

当从对象上下文中调用方法时,伪变量 $this 可用。 $this 是对调用对象的引用(通常是方法所属的对象,但也可能是另一个对象,如果该方法是从辅助对象的上下文中静态调用的)。从 PHP 7.0.0 开始,从不兼容的上下文中静态调用非静态方法会导致 $this 在方法内部未定义

【讨论】:

  • 很高兴为此也包含了一个准备好的声明。
  • @FunkFortyNiner 是的,我想我会为安全代码的未来准备 OP(双关语;))
  • 哈哈哈! - 嘿,好一个;-)
【解决方案2】:

$this 是当前调用对象的引用,或者我们可以说该对象正在使用中。当您使用多个类实例时,您的代码库将可以针对不同的实例进行管理。此外,可见性允许您想要保持私有或公开的内容。并且$this 将在您设置后在整个对象生命周期中工作,您可以接受对象/类范围内的任何位置,而不仅限于函数。

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-24
    • 2015-10-25
    • 1970-01-01
    相关资源
    最近更新 更多