Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
265 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...