简体   繁体   English

如何解决未定义变量和未定义属性警告?

[英]How to solve undefined variable and undefined property warnings?

I have $name and $age defined in set_name() and set_age .我在set_name()set_age中定义了$name$age Please check index.php:请检查 index.php:

<?php
// This part needs some fixing.
class Pet {
    public $name;
    public $age;    

    // get() and set() functions for name
    function set_name($name) {
        $this->name = $name;
    }
    function get_name() {
        return $this->$name;
    }

    // get() and set() functions for age
    function set_age($age) {
        $this->age = $age;
    }
    function get_age() {
        return $this->$name;
    }
}
.....

Edit: This problem is fixed.编辑:此问题已修复。 No need for new answers!不需要新的答案!

You need constructor for your classes and don't do the makeSound method in your Pet class static .您的类需要构造函数,并且不要在 Pet class static中执行makeSound方法。 Try this:尝试这个:

public Cat(){
  makeSound(sound);
}

public Dog(){
  makeSound(sound);
}

Your method declaration is wrong.你的方法声明是错误的。 If a parent has an implemented version of a function, you do not need to declare it in the subclass.如果父类有一个 function 的实现版本,则不需要在子类中声明它。 But even if you would want to, the correct way to do it (thus overriding the parent function) would be:但即使您愿意,正确的方法(从而覆盖父函数)也是:

void makeSound(String sound) {
        System.out.println("Hi, I make a " + sound);
    }

The use of a static keyword would not make much sense.使用 static 关键字没有多大意义。 A static method is a method that is part of the class and not of the created objects. static 方法是属于 class 而不是创建的对象的方法。 Meaning you could call the method like this Pets.makeSound(...)这意味着您可以像这样调用方法Pets.makeSound(...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM