gpt4 book ai didi

php - 如何从网页函数中调用php类中的函数

转载 作者:行者123 更新时间:2023-11-30 13:12:24 24 4
gpt4 key购买 nike

代码示例;

PHP 网页:(index.php)

 <html><head></head>
<body>
<?php
include("class_validation.php");
$val = new validation();

if(isset($_POST['action'])) doSomething();

function doSomething() {
$val->validate(); //I AM UNABLE TO DO THIS!
}
?>
</body>
</html>

PHP 文件:(class_validation.php)

<?php
class validation()
{
function validate(){
//some validation
}
}
?>

问题:如何在我的 PHP 网页中创建的函数中调用“class_validation.php”文件中的函数?我可以正确调用函数 doSomething() 以及调用函数 $val->validate();当不在另一个函数中时。我有办法做到这一点吗?

最佳答案

$val 超出了 doSomething() 函数调用的范围。将其作为参数传递给函数:

// Define the function to accept a parameter. Use a type hint to be sure it is 
// a validation object
function doSomething(validation $val) {
$val->validate();
}

if(isset($_POST['action'])) doSomething($val);

( PHP documentation on type hinting )

或者,不推荐,您可以在函数内使用 global 关键字来引用全局 $val.

function doSomething() {
// Don't do it this way. The func parameter is preferred
global $val;
$val->validate();
}

关于php - 如何从网页函数中调用php类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13409663/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com