PHP-OOP-为什么我的函数被调用两次? [英] PHP - OOP - Why is my function called twice?

查看:93
本文介绍了PHP-OOP-为什么我的函数被调用两次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我面临的问题是,每次提交表单时,函数都会被调用两次

I'm facing a problem that my function is called twice everytime i submit my form

我的表单文件,其中包含对函数的调用:

my form file with the call to the function:

<?php
require "classes/loginClass.php";
$login = new login;
$login->login();
?>

<form action="" method="POST">
    <label for="username">username: </label>
    <input type="text" id="username" name="username" required><br/>
    <label for="password2">password: </label>
    <input type="password" id="password2" name="password2" required><br/>
    <input type="submit" name="submit" value="login">
</form>

我的类和功能:

class login {

    public function login() {
        if(isset($_POST['submit'])){
            echo "submit";
        }
    }
}

因此,每当我按下提交"按钮时,提交"都会被呼应两次.这意味着我的函数被调用了两次.我不太明白为什么.

So everytime when i press the submit button, "submit" get echoed twice. Which means my function is called twice. I do not quite get why.

推荐答案

与该类相同名称的方法被视为(旧样式)构造函数,并且每次创建对象时都会调用该方法.

A method named the same as the class is considered an (old style) constructor, and is called every time the object is created.

因此,在创建对象时将调用它一次,而在显式调用它时将调用它.

So it's called once when the object gets created, and another time when you explicitly call it.

请注意,今天,实现__construct()而不是ClassName()被认为是更好的做法,主要是为了帮助继承.

Note that today, it's considered a better practice to implement __construct() rather than ClassName(), mainly to help with inheritance.

更多阅读材料:

这篇关于PHP-OOP-为什么我的函数被调用两次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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