PHP:在构造函数中调用用户定义的函数?
我在其构造函数中有一个类 userAuth
我添加了代码来检查用户是否有效,如果会话中没有值,那么我检查cookie(作为“记住我”功能的一部分) ,如果 cookie 中有一些值,那么我调用函数 ConfirmUser
从数据库检查其真实性。根据confirmUser函数返回的值,我在构造函数中返回一个bool(true或fales)值。
我将我的类创建为:
<?php
class userAuth {
function userAuth(){
//code
}
function confirmUser($username, $password){
//code
}
}
$signin_user = new userAuth();
?>
confirmUser
函数接受两个字符串类型参数并返回整数值 0、1、2。
我无法添加 confirmUser
函数的代码在构造函数内,因为我在应用程序的其他地方使用此函数。
所以,我想知道如何在 PHP 的构造函数中调用用户定义的函数。请帮忙。
谢谢!
I have a class userAuth
inside its constructor I have added code to check the user is valid or not, if there is no value in session then I check cookies (as a part of "Remember Me" feature), if there is some value inside cookies then I call a function ConfirmUser
to check its authenticity from database. On the basis of value returned by the confirmUser function I am returning a bool (true or fales) value in constructor.
I have created my class as:
<?php
class userAuth {
function userAuth(){
//code
}
function confirmUser($username, $password){
//code
}
}
$signin_user = new userAuth();
?>
confirmUser
function take two string type parameters and return return a integer value of 0, 1, 2.
I can't add code of confirmUser
function inside the constructor as I am using this function at some more places in my application.
So, I want to know how to call a user-defined function inside constructor in PHP. Please help.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
$this->nameOfFunction()
但是当它们在一个类中时,它们被称为方法。
$this->nameOfFunction()
But when they are in a class, they are called Methods.
不过,在构造函数中使用 $this 时要小心,因为在扩展层次结构中,它可能会导致意外行为:
输出:
而:
输出:
Be careful with using $this in a constructor, though, because in an extension hierarchy, it can cause unexpected behaviour:
Output:
Whereas:
Output:
在构造函数内部调用函数和从其他地方调用函数没有区别。如果该方法在同一个类中声明,则应使用
$this->function()
顺便说一下,在 php5 中,建议您这样命名构造函数:
function __construct()
如果没有,则在构造函数定义之前放置
public
关键字,如下所示public function userAuth()
There is no difference between calling a function inside a constructor and calling from somewhere else. If the method is declared in the same class you should use
$this->function()
By the way, in php5 you are suggested to name your constructor like this:
function __construct()
If not then put
public
keyword before your constructor definition like thispublic function userAuth()
你可以用 $this 打电话
you can call with $this