将类的实例传递给php中的另一个文件

时间:2017-05-15 19:29:21

标签: php

我是PHP OO编程的新手。我对OOP有基本的了解。我正在从程序转换到OOP,我在将一个类的实例传递给php中的另一个文件时遇到了一些问题。

我已经读过某个地方,如果你想将一个类的实例传递给另一个php文件,你需要:

testA.php

$user = new User($login);

testB.php

require_once('testA.php');
echo $user->getLogin();

这很酷,它可以很好地用于一个简单的例子。它按预期显示登录名。现在让我们来看一个更复杂的例子。

我有一个表单,用户输入了他的loginpassword。此表单已发送至login-exec.php。完成验证后,类loginIntoWebsite()中的方法User会将用户重定向到member-profile.php。我的问题就在这里开始。在我的member-profile.php中,我填写了login-exec.php的必要内容。

一个简单的逻辑图:form -> login-exec.php -> User::loginIntoWebsite() -> member-profile.php

logic-exec.php

...
$user = new User($login, $password);
    if($user->loginIntoWebsite()){
        header("location: member-profile.php");
    }else{
        header("location: login-failed.php");
    }
    exit();

User::loginIntoWebsite()

//validations and mysql queries above 
if(password_verify($password, $passwordHashDB)){
     //Login Successful
     $this->attributeValuesToAttributes($memberID, $firstName, $lastName, $profilePicture, $moneyAmount);
     $_SESSION['LOGIN_USER'] = $login;
     $_SESSION['SESS_MEMBER_ID'] = $memberID;
     $_SESSION['SESS_FIRST_NAME'] = $firstName;
     $_SESSION['SESS_LAST_NAME'] = $lastName;
     $_SESSION['SESSION_ID'] = session_regenerate_id();
     session_write_close();
     return true;
}else{
     return false;
}

member-profile.php

include('login-exec.php');
if(isset($user)){
    echo "user is set in member-profile.php";
    echo $user->getLogin();
}else{
    echo "uset is not set in member-profile.php";
}

正如您猜测的那样,它回显了user is not set in member-profile.php". Does it have anything to do with the标题(“location:member-profile.php”);`?

1 个答案:

答案 0 :(得分:0)

<强>答 - 观点

这部分:

testA.php:

$user = new User($login);
testB.php:

require_once('testA.php');
echo $user->getLogin();
  

这很酷,而且效果很好

是。它有效,但它不酷

我正在进一步查看你的代码......实际上,你正试图用OOP制作东西而不知道它应该如何工作&#34;对&#34;。您正在使用classes&amp; objects,但你的思想仍然在&#34; procedural style&#34;。你会有更多的&amp;进一步的问题。它不是&#34;对&#34;对于这些内容采用OOP方式(例如,现在我看到了 - 您希望像"Autorization"&amp; including files这样的实现类似于"routing")。

建议:开始阅读有关基本模式(Singelton等)的内容,然后按常用词汇MVC,选择最简单的MVC-framevork等。总结:目前你没有上正确的方式