如何在php中定义类的属性? [英] How Do I define properties for a class in php?

查看:101
本文介绍了如何在php中定义类的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据阅读的内容,我收到了不同的答复。

I've received Mixed responses on this depending what walk-through I read,

我定义了一个具有2个功能的类。

I've defined a class with 2 functions.

我希望两个功能都可以访问数据库凭据

I want both functions to have access to the DB credentials

当前,除非我不执行此代码将变量复制并粘贴到每个函数中。

Currently, this code does not work unless I Copy and paste the variables into each function.

我在这里做什么错了?

<?php
class database  {
function connect()  {
var $username="my_username";
var $servername="localhost";
var $database="my_DB";
var $password="An_Awesome_Password";
var $con;
    $con = mysql_connect($servername,$username,$password);

    if (!$con)  {
    die('Could not connect: ' . mysql_error());
                }
                    }

function disconnect()   {
    $con = mysql_connect($servername,$username,$password);

    if (!$con)  {
    die('Could not connect: ' . mysql_error());
                }
    mysql_close($con);
                        }
            }
?>


推荐答案

此块:

var $username="my_username";
var $servername="localhost";
var $database="my_DB";
var $password="An_Awesome_Password";
var $con;

应该在 function()之前,不在里面;但仍在定义之内。

Should come before the function(), not inside it; but still inside the class definition.

这是添加显式可见性的好形式;私有开始于:

And it's good form to add an explicit visibility; private to start with:

class database  {
    private $username="my_username";
    private $servername="localhost";
    // etc. etc.

然后,函数将它们称为:

Then, the functions refer to them as:

$this->username;
$this->con;
etc.






理想的情况是具有构造函数要传递的凭据:


Ideally you will want to have those credentials to be passed in by the constructor:

private $servername;
private $database;
private $username;
private $password;
private $con;

function __construct($host, $user, $password, $dbname)
{
    $this->servername = $host;
    $this->username = $user;
    $this->password = $password;
    $this->database = $dbname;
}






更理想的是学习关于 PDO

这篇关于如何在php中定义类的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆