为什么函数__construct在PHP中不起作用?

时间:2015-09-27 01:05:00

标签: php mysqli

有人可以解释

为什么这不起作用?

<?php
class category
{
    function __construct()
    {
        $con = new mysqli("localhost", "root", "", "whatever");
    }

    function show_all()
    {
        $sql = "SELECT id_kategori, nama_kategori FROM kategori";
        $stmt = $con->prepare($sql);
        $stmt->execute();
        $stmt->bind_result($id, $cat);
        while($stmt->fetch())
        {
            echo "<td>$id</td>";
            echo "<td>$cat</td>";
            echo "<td>Update</td>";
            echo "<td>Delete</td>";
        };
        $stmt->close();
    }

}
?>

但这有效吗?

<?php
class category
{

    function show_all()
    {
        $con = new mysqli("localhost", "root", "", "whatever");
        $sql = "SELECT id_kategori, nama_kategori FROM kategori";
        $stmt = $con->prepare($sql);
        $stmt->execute();
        $stmt->bind_result($id, $cat);
        while($stmt->fetch())
        {
            echo "<td>$id</td>";
            echo "<td>$cat</td>";
            echo "<td>Update</td>";
            echo "<td>Delete</td>";
        };
        $stmt->close();
    }

}
?>

如果没有构造,它就会起作用,构建它不会。

有人可以告诉我,告诉我,如何以正确的方式教我如何在构造中包含sql连接?我还是新手,顺便学习。

2 个答案:

答案 0 :(得分:3)

这是因为范围界定。 $con变量应该被定义为专门在类中使用,而不是仅在__construct内部使用。

当您在$con中定义__construct时,您要在函数__construct内部而不是在类本身中本地使用

考虑以下代码

<?php
class category
{
    private $con;

    function __construct()
    {
        $this->con = new mysqli("localhost", "root", "", "whatever");
    }

    function show_all()
    {
        $sql = "SELECT id_kategori, nama_kategori FROM kategori";
        $stmt = $this->con->prepare($sql);
        $stmt->execute();
        $stmt->bind_result($id, $cat);
        while($stmt->fetch())
        {
            echo "<td>$id</td>";
            echo "<td>$cat</td>";
            echo "<td>Update</td>";
            echo "<td>Delete</td>";
        };
        $stmt->close();
    }

}
?>

答案 1 :(得分:2)

$ con不是上述类中可访问的变量:试试这个:

<?php
class category
{

    private $con = NULL;

    function __construct()
    {
        $this->con = new mysqli("localhost", "root", "", "whatever");
    }

    function show_all()
    {
        $sql = "SELECT id_kategori, nama_kategori FROM kategori";
        $stmt = $this->con->prepare($sql);
        $stmt->execute();
        $stmt->bind_result($id, $cat);
        while($stmt->fetch())
        {
            echo "<td>$id</td>";
            echo "<td>$cat</td>";
            echo "<td>Update</td>";
            echo "<td>Delete</td>";
        };
        $stmt->close();
    }

}
?>

在这里查看文档: http://php.net/manual/en/language.oop5.php 并查找php范围: http://php.net/manual/en/language.variables.scope.php

此外,如果您有任何疑问,请始终将其添加到您的代码中: 这会告诉你变量是未定义的:

error_reporting(E_ALL);
ini_set('display_errors', '1');