Php面向对象,函数调用

时间:2014-01-30 22:19:16

标签: php function object call

这是我的php页面 persona.php

<?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很简单,只显示构造函数和一个在调用时更改两个用户名的函数。

这是 index.php

<?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函数。

2 个答案:

答案 0 :(得分:2)

我可以理解引起混淆的地方......我想您不确定是否应该在changename$utente1上致电$utente2。从技术上讲,您可以从任一对象调用它,因为它们都是Persona

的实例

但为了清晰(和理智),我建议在其声明中将changeName函数转换为static function

public static function changeName($utente1,$utente2){

然后在index.php中,您可以将其命名为:

Persona::changename($utente1,$utente2);

从架构标记点来看,这将有助于更好地理解函数与Persona类相关联,并且对象可以使用该类函数更改交换名称,而不是使其成为实例函数然后具有任何对象执行它。

答案 1 :(得分:0)

在您的特定情况下,您可以将其命名为:

$utente1->changename($utente1,$utente2);
or
$utente2->changename($utente1,$utente2);

哪个没关系。由于方法本身不适用于类属性(但只能使用方法参数),因此可以从任何存在的对象中调用它。

但更好(最佳实践,更好的设计)是开发一种静态方法,正如Raidenace所说,并称之为:

Persona::changename($utente1,$utente2);