PHP:在类中使用isset()函数

时间:2016-02-01 09:52:15

标签: php

我从事过程编程,是OOP的新手。使用以下代码,我想在单击提交按钮上打印“已成功提交”消息。但它没有发生。在程序编程中,我做了类似isset($ _ POST [$ name])的操作。这里如何引用按钮名称?

<?php

//myclass

class InsertData {
    public $txtwidth;
    public $txtheight;
    public $txtname;
    public $btnwidth;
    public $btnheight;
    public $btnname;

    function setTextField($tw, $th, $tname) {
        $this->txtwidth = $tw;
        $this->txtheight =$th;
        $this->txtname = $tname;        
    }

    function setButton($bw, $bh, $bname) {
        $this->btnwidth = $bw;
        $this->btnheight =$bh;
        $this->btnname = $bname;
    }

function displayText() {
    if(isset($_POST[$this->btnname])) {         
            echo "Submitted successfully";
        }
}
    function getTextField() {
        $str = "<form name='inputform' action='#' method='post'>
        <input type='text' name='".$this->txtname."' Style=width:".$this->txtwidth."px;height:".$this->txtheight."px><br><br>
         <input type='submit' name='".$this->btnwidth."' Style=width:".$this->btnheight."px;height:".$this->btnname."px>
         </form>";  


        return $str;
    }

}
?>

我的代码

<?php

//my code

include "InsertData.php";
$txt = new InsertData();

$txt->setTextField(800,200,'yourname');
$txt->setButton(100, 200, 'click');
echo $txt->getTextField();
echo $txt->displayText();
?>

3 个答案:

答案 0 :(得分:3)

检查此功能,您可以交换宽度,名称和高度的值

function getTextField() {
        $str = "<form name='inputform' action='#' method='post'>
        <input type='text' name='".$this->txtname."' Style=width:".$this->txtwidth."px;height:".$this->txtheight."px><br><br>
         <input type='submit' name='".$this->btnname."' Style=width:".$this->btnwidth."px;height:".$this->btnheight."px>
         </form>";  


        return $str;
    }

答案 1 :(得分:2)

只需将函数displayText()修改为

即可
function displayText() {
  return "Submitted successfully";
}

在提交时做一个,

if(isset($_POST['your_btn_name'])) {   
  echo  $txt->displayText();    
}

答案 2 :(得分:0)

尝试将其作为参数传递给classes函数,例如:

<?php
class Foo
{
    public function showMessage($message = '')
    {
        if ($message != '')
        {
            print "You submitted: {$message}";    
            return;    
        }
        print "Message failed to send...";
        return;
    }
}

$foo = new Foo();
?>
<form action="#" method="post">
    <input type="text" name="message" />
    <br />
    <input type="submit" name="submit" value="Submit my message!" />
</form>
<?php
if (isset($_POST['submit']))
{
    $foo->showMessage($_POST['message']);
}

没有消息,它说:消息无法发送......
并通过消息说明:您提交的内容:消息(我使用了消息的消息)