Php面向对象,函数调用 [英] Php Object oriented, Function calling
问题描述
这是我的php页面 persona.php :
<?php
级角色{
private $ name;
public function __construct($ n){
$ this-> name = $ n;
}
public function getName(){
return $ this-> name;
public function changeName($ utente1,$ utente2){
$ temp = $ utente1-> name;
$ utente1-> name = $ utente2-> name;
$ utente2-> name = $ temp;
}
}
?>
<?php
require_oncepersona.php;
$ utente1 =新角色(Marcello);
打印第一个用户:< b>。 $ utente1->的getName()。 < / B><峰; br><峰; br> 中;
$ utente2 =新角色(Sofia);
打印第二位用户:< b>。 $ utente2->的getName()。 < / B><峰; br> 中;
changename($ utente1,$ utente2);
print名称更改后测试:第一个用户。 $ utente1-> getName()。< / b>第二位用户。 $ utente2->的getName();
?>
我不明白如何调用 changeName
函数来自这里。
我可以理解混淆的起因在哪里...我想你不确定你是否应在 $ utente1
或 $ utente2
上调用 changename
。从技术上讲,你可以从任何一个对象中调用它,因为它们都是 Persona
的实例。但是为了清晰(和理智) ,我会建议在其声明中将 changeName
函数转换为静态函数
public static function changeName($ utente1,$ utente2){
然后在你的index.php你可以这样称呼它:
从体系结构标记点来看,这有助于更好地理解该函数与Persona类绑定,并且对象可以使用该类函数更改交换名称,而不是使它成为实例函数,然后让任何对象执行它。 This is my php page persona.php: The class This is index.php: What I do not understand is how to call the I can understand where the confusion arises from...I think you are unsure if you should call But for clarity (and sanity), I would recommend converting the and then in your index.php you can call it as: From an architecture stamp point, this will help provide a better sense that the function is tied to the class of Persona, and objects can change swap names using that class function, as opposed to making it an instance function and then having any object execute it. 这篇关于Php面向对象,函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
<?php
class persona {
private $name;
public function __construct($n){
$this->name=$n;
}
public function getName(){
return $this->name;
}
public function changeName($utente1,$utente2){
$temp=$utente1->name;
$utente1->name=$utente2->name;
$utente2->name=$temp;
}
}
?>
persona
is simple and just shows the constructor and a function that change two users name if called.<?php
require_once "persona.php" ;
$utente1 = new persona("Marcello");
print "First user: <b>". $utente1->getName()."</b><br><br>";
$utente2 = new persona("Sofia");
print "Second user: <b>". $utente2->getName()."</b><br>";
changename($utente1,$utente2);
print " Test after name changes: first user". $utente1->getName()."</b> second user". $utente2->getName();
?>
changeName
function from here.changename
on $utente1
or $utente2
. Technically you can call it from either objects because they are both instances of Persona
changeName
function to a static function
in its declaration:public static function changeName($utente1,$utente2){
Persona::changename($utente1,$utente2);