Php Object oriented, Function calling

a 夏天 提交于 2019-12-13 09:39:30

问题


This is my php page 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;

    }
}
?>

The class persona is simple and just shows the constructor and a function that change two users name if called.

This is 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();
?>

What I do not understand is how to call the changeName function from here.


回答1:


I can understand where the confusion arises from...I think you are unsure if you should call changename on $utente1 or $utente2. Technically you can call it from either objects because they are both instances of Persona

But for clarity (and sanity), I would recommend converting the changeName function to a static function in its declaration:

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

and then in your index.php you can call it as:

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

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.




回答2:


In your particular case you can call it as:

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

It doesn't matter which. As the method itself doesn't work with the classes properties (but only with the method parameters), you can call it from any object that exist.

But better (best practice, and better by design) is to develop a static method, as Raidenace already said, and call it like:

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


来源:https://stackoverflow.com/questions/21468632/php-object-oriented-function-calling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!