-1
class db
{
    function connect()
    {
        $lines    = file('secret');
        $uid      = trim($lines[0]);
        $pw       = trim($lines[1]);
        $dbserver = trim($lines[2]);
        $dbname   = trim($lines[3]);

        $link = mysqli_connect($dbserver, $uid, $pw, $dbname) or die('Could not connect: ' . mysqli_error());
        return $link;
    }
    function query($sql)
    {
        $result = mysqli_query($this->connect(), $sql) or die('query failed' . mysqli_error());
        return $result;
    }
    function close()
    {
        mysqli_close($this->connect());
    }
}

//任何人都可以切换这些代码以包含私有成员吗?//我尝试了很多东西,但每次都失败

4

1 回答 1

1

可以使用private关键字设置私有类属性。

更多信息:PHP 手册:可见性

例如:

<?php
/**
 * Define MyClass
 */
class MyClass
{
    public $public = 'Public';
    protected $protected = 'Protected';
    private $private = 'Private';

    function printHello()
    {
        echo $this->public;
        echo $this->protected;
        echo $this->private;
    }
}

$obj = new MyClass();
echo $obj->public; // Works
echo $obj->protected; // Fatal Error
echo $obj->private; // Fatal Error
$obj->printHello(); // Shows Public, Protected and Private
于 2013-08-08T02:19:54.033 回答