我有一个类似于下面的类构造函数(我把一些变量遗漏了),但是我不知道如何构造一个对象并向它发布变量。我继承了这段代码,所以我知道它有效但不确定如何...有人可以告诉我这里发生了什么吗?如何创建对象并设置所有这些参数?
function __construct()
{
$some variables set here
$user_name = isset($_POST['user_name']) ? prepare_input($_POST['user_name'], true) : '';
$password = isset($_POST['password']) ? prepare_input($_POST['password'], true) : '';
//some more post variables
$this->wrongLogin = false;
if(!$this->IsLoggedIn()){
if($submit_login == 'login'){
if(empty($user_name) || empty($password)){
if(isset($_POST['user_name']) && empty($user_name)){
$this->loginError = '_USERNAME_EMPTY_ALERT';
}else if(isset($_POST['password']) && empty($password)){
$this->loginError = '_WRONG_LOGIN';
}
$this->wrongLogin = true;
}else{
$this->DoLogin($user_name, $password, $remember_me);
}
}else{
if(isset($_COOKIE[$this->cookieName])){
parse_str($_COOKIE[$this->cookieName]);
if(!empty($type) && !empty($usr) && !empty($hash)){
$this->accountType = $type;
$user_name = $usr;
$password = $this->Decrypt($hash, $this->passwordKey);
$this->DoLogin($user_name, $password, '2');
}
}
}
}else if($submit_logout == 'logout'){
$this->DoLogout();
}
答案 0 :(得分:0)
我不知道这里的问题是什么,但你可以这样做:
class MyClass {
public $var1;
public $var2;
function __construct($var1, $var2 = 5){
$this->var1 = $var;
$this->var2 = $var2;
}
}
代码中的某个地方
// we can skip passing 2nd parameter
$myObject = new MyClass(10);
答案 1 :(得分:0)
$ _ POST变量,例如:
<?php
class my_class {
public $status; // PROPERTY.
public $user; // PROPERTY.
public $pass; // PROPERTY.
function __construct ()
{ $this->user = ( isset( $_POST["user"] ) ) ? $_POST["user"] : ""; // PROPERTY.
$this->pass = ( isset( $_POST["pass"] ) ) ? $_POST["pass"] : ""; // PROPERTY.
if ( ( strlen( $this->user ) == 0 ) ||
( strlen( $this->pass ) == 0 ) )
$this->status = false; // PROPERTY.
else $this->status = true; // PROPERTY.
}
}
$myc = new my_class();
$_POST["user"] = "abc"; // HERE $_POST VARIABLES ARE DEFINED AFTER
$_POST["pass"] = "123"; // THE CLASS IS BEEN INSTANTIATED.
if ( $myc->status )
echo "Good";
else echo "Bad";
?>
它将显示“Bad”,因为实例化类时$ _POST变量不存在,因此构造函数将“”分配给属性。