gpt4 book ai didi

php - 如何给 PHP 中的函数起有意义的名称?

转载 作者:行者123 更新时间:2023-12-01 22:49:13 25 4
gpt4 key购买 nike

这可能看起来是一个愚蠢而琐碎的问题。我在 PHP 中命名函数时遇到问题。我有两个函数可以根据学生的 ID 或姓名和电子邮件检索学生的所有信息。

由于 PHP 没有与 JAVA 相同意义上的函数重载,因此我很难命名函数。

这就是我所做的。这些是我给它们起的名字。

get_students_with_id($id)get_students_with_name_and_email($name, $email)

但是参数会增加。我需要一个更好、更简单的解决方案来命名这些函数或方法。顺便说一句,他们都属于同一类。那我该怎么办?提前致谢。

最佳答案

在 PHP 中,不存在像 JAVA 中那样的方法覆盖的概念,但是您可以发送默认参数,例如:

get_students($id, $name = null, $email = null)

这意味着您不需要使用三个参数来调用该函数。你可以通过只用 1 来调用它,它会假设它是 id。例如,如果您想让一个函数适用于上面的示例,您可以执行以下操作:

function get_students($id, $name = null, $email) {
if (!empty($id)) {
// Get students by their ids
} else if (!empty($name) && !empty($email)) {
// Get students by their names and emails
}
}

你可以调用上面的函数:

get_students(1); //Will retrieve studen with id 1
get_students(null, "Name", "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3e5b535f57527e5b535f5752105d5153" rel="noreferrer noopener nofollow">[email protected]</a>"); //Will retrieve students with name "Name" and email "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3f5a525e56537f5a525e5653115c5052" rel="noreferrer noopener nofollow">[email protected]</a>"

关于php - 如何给 PHP 中的函数起有意义的名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31259235/

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