PHP类::为什么要声明为新的? [关闭]

I'm very new to php classes and I was wonder why do I need to declare it to a variable and set it as NEW?

Here is an example :

class myFirstClass {
    function Version(){
        return 'Version 1';
    }
    function Info(){
        return 'This class is doing nothing';
    }
}

$hola = new myFirstClass;

echo $hola->Version();

Why this won't work WITHOUT declare it to a variable and set it to NEW ?

In other words... Without this line :

$hola = new myFirstClass;

I'm so used to functions so it looks weird to me...

You are right! It is not necessary to use the new operator:

class myFirstClass {
    static function Version(){// static keyword
        return 'Version 1';
    }
    function Info(){
        return 'This class is doing nothing';
    }
}

echo myFirstClass::Version();// direct call

To create an instance of a class, the new keyword must be used. An object will always be created unless the object has a constructor defined that throws an exception on error. Classes should be defined before instantiation (and in some cases this is a requirement).

If a string containing the name of a class is used with new, a new instance of that class will be created. If the class is in a namespace, its fully qualified name must be used when doing this.

The Basics

http://php.net/manual/en/language.oop5.basic.php

Classes and Objects

http://php.net/manual/en/language.oop5.php

This line:

$hola = new myFirstClass;

Is saying: create a new object called $hola, then put a new instance of myFirstClass into $hola. Now $hola is literally a object containing a new instance of myFirstClass.

This is a basic principle of Object Oriented Programming (OOP). Let's use a library system for example. If you want to get the name of a book, you cannot just say "give me the name of the book", you have to know what book (by id, author, whatever).

In functions, you can write one that looks like this:

function get_book($id){ // code }

In OOP it doesn't really work that way. You have a class book that keeps a name. But that name is only for that given book.

class Book {
  var $name;
  public __construct($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

In order to call the getName() function we need to have a book. This is what new does.

$book = new Book("my title");

Now if we use the getName() function on $book we'll get the title.

$book->getName(); // returns "my title"

Hope that helps.