I have $name and $age defined in set_name() and set_age.
Please check 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. 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. 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. A static method is a method that is part of the class and not of the created objects. Meaning you could call the method like this Pets.makeSound(...)
Related
To define properties in the class, I see two ways:
1
create public variables first, and refer to them inside the __construct() function:
<?php
class User {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function getType() {
return $this->type;
}
} ?>
And simply define the properties without defining the public variables:
2
<?php
class Cars{
function __construct($parameter1, $parameter2) {
$this->model= $parameter1;
$this->price = $parameter2;
}
function getPrice(){
echo $this->price ."<br/>";
}
function getModel(){
echo $this->model ." <br/>";
}
} ?>
I'm wondering what is the different usages of these two approaches to define the properties for class in PHP? What's point of using the first option when second option is working the same?
As you said, solution 1 and 2 works but the solution 2 is just a bad way to declare class variables.
By strict convention, always declare your class variables:
You can see the variables of your class in one look. And think about others developers which look after you, it's important to know which variables we can find in this class.
You can define visibility of variables (public, protected, private).
(PHP7) I have two classes but would like to access one class inside of another for example:
Syntax: Property::House()->getAddress();
class Property
{
protected $House;
function Property()
{
self::$House = new House();
}
public function House()
{
return self::$House;
}
}
class House
{
public function getAddress()
{
// code
}
}
does anyone know to accomplish this?, the syntax needs to be the same but the classes can change if needed
Firstly, your class setup is going to give you deprecation errors in PHP7. You'd be better off using the __construct() method in place of Property() if you're wanting to use non-static calls.
Secondly. Are you sure you don't want House to extend the Property class instead of being a property of the Property class?
Thirdly, assuming you're sure of what you're trying to achieve this should work...
<?php
class Property
{
static function House()
{
return new House();
}
}
class House
{
public function getAddress()
{
echo 'YAY!';
}
}
Property::House()->getAddress();
class User {
public $name;
public function __construct($name) {
$this->name = $name;
}
public function sayHi() {
echo "Hi, I am $this->name!";
}
}
Can someone explain to me word by word, what is meant by $this->name=$name?
I keep thinking like, $this goes into(hence the -> sign) name which is (hence the = sign) $name defined beforehand.
Also I dont see the need of that function?
Could just go like this :
class User {
public $name;
public function sayHi() {
echo "Hi, I am $name!";
}
}
I'm out of idea thinking about this .. thanks in advance.
When you are creating a new instance of the class User with the __construct parameter $name, by $this->nameit is set to the $name property of the class. In your second example $name does not get any value because you are nowhere assigning any value to it.
You could also have it like this for better understanding:
class User {
public $nameProperty;
public function __construct($name) {
$this->nameProperty = $name;
}
public function sayHi() {
echo "Hi, I am $this->nameProperty!";
}
}
$this refers to the class you are currently in. So when you create a new class of User, you can pass a name by using the $name parameter. This parameter then gets assigned to the $nameProperty and in your method sayHi() you would then echo the assigned name.
class User {
public $name; //declare a public property
public function __construct($name) {
$this->name = $name;
/* at the time of object creation u have to send the value & that value will be store into a public property which will be available through out the class. like $obj = new User('Harry'); Now this will be set in $this->name & it is available inside any method without declaration.
*/
}
public function sayHi() {
echo "Hi, I am $this->name!"; //$this->name is available here
}
}
In the context of a class method, when you want to access the class properties, you have to use $this->property. Without $this, you are actually accessing a variable in the scope of the method, which in your case, is the parameter $name.
The function __construct() is the constructor for your class object. So if you would instantiate an object, you would execute the code inside the constructor. Example:
$user = new User("John"); // you are actually calling the __construct method here
echo $user->name; // John
Hope that enlightens you.
I am currently digging into the basics of php class / constructor.
I understand how a constructor works but not why I should use it.
For example when I have a constructor like this:
function __construct($arg1, $arg2){
$this->name = $arg1;
$this->speed = $arg2;
}
Why should I use __constructor and not a simple callback like:
function foo($arg1,$arg2){
$this->name = $arg1;
$this->speed = $arg2;
}
Thank you
Doing
$obj = new Class($var1, $var2);
And
$obj = new Class($var1, $var2);
$obj->foo($var1, $var2);
Have the same end result
By forcing values to be passed on the constructor, class can define Mandatory values it should have in order to construct a class. As in the later case, one can ignore foo.
Having a method to initialize means, one ends up having different method names, foo, init etc, constructor avoids this
The constructor is always called on object instantiation and is a known pattern.
Your second example isn't (if it's intended to perform a similar initialisation role as the constructor).
<?php
class abc {
function __construct($arg1, $arg2){
echo $arg1.' '.arg2;
}
}
$obj = new abc('manish','jangir');
?>
It will print "manish jangir" automatically when the object is created
The main purpose is to keep your code clean. With placing your initialization in the constructor you can kan be sure the variable to be used in the other function will be in valid state for example :
class Foo{
private $number;
public function setNumber($number) {
$this->number = $number;
}
public function getNumber() {
if ($this->number=== null) {
throw new RuntimeException("The Number is Null !");
}
return number;
}
}
this is the class with constructor
class Foo{
private $number;
public function __construct($number) {
$this->number = $number;
}
public function getNumber() {
if ($this->number=== null) {
throw new RuntimeException("The Number is Null !");
}
return number;
}
}
with constructor you can be sure the number will be initialized. I hope my answer is clear enough but if you have another question about my answer feel free to ask in the comment :)
When would you use the $this keyword in PHP? From what I understand $this refers to the object created without knowing the objects name.
Also the keyword $this can only be used within a method?
An example would be great to show when you can use $this.
A class may contain its own constants, variables (called "properties"), and functions (called "methods").
<?php
class SimpleClass
{
// property declaration
public $var = 'a default value';
// method declaration
public function displayVar() {
echo $this->var;
}
}
?>
Some examples of the $this pseudo-variable:
<?php
class A
{
function foo()
{
if (isset($this)) {
echo '$this is defined (';
echo get_class($this);
echo ")\n";
} else {
echo "\$this is not defined.\n";
}
}
}
class B
{
function bar()
{
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
}
}
$a = new A();
$a->foo();
// Note: the next line will issue a warning if E_STRICT is enabled.
A::foo();
$b = new B();
$b->bar();
// Note: the next line will issue a warning if E_STRICT is enabled.
B::bar();
?>
The above example will output:
$this is defined (A)
$this is not defined.
$this is defined (B)
$this is not defined.
The most common use case is within Object Oriented Programming, while defining or working within a class. For example:
class Horse {
var $running = false;
function run() {
$this->running = true;
}
}
As you can see, within the run function, we can use the $this variable to refer to the instance of the Horse class that we are "in". So the other thing to keep in mind is that if you create 2 Horse classes, the $this variable inside of each one will refer to that specific instance of the Horse class, not to them both.
You would only use $this if you are doing Object Oriented programming in PHP. Meaning if you are creating classes. Here is an example:
class Item {
protected $name, $price, $qty, $total;
public function __construct($iName, $iPrice, $iQty) {
$this->name = $iName;
$this->price = $iPrice;
$this->qty = $iQty;
$this->calculate();
}
}
$this is used to make a reference to the current instance of an object.
So you can do things like:
class MyClass {
private $name;
public function setName($name) {
$this->name = $name;
}
//vs
public function setName($pName) {
$name = $pName;
}
}
Also another cool use is that you can chain methods:
class MyClass2 {
private $firstName;
private $lastName;
public function setFirstName($name) {
$this->firstName = $name;
return $this;
}
public function setLastName($name) {
$this->lastName = $name;
return $this;
}
public function sayHello() {
print "Hello {$this->firstName} {$this->lastName}";
}
}
//And now you can do:
$newInstance = new MyClass2;
$newInstance->setFirstName("John")->setLastName("Doe")->sayHello();
It's used in Object-oriented Programming (OOP):
<?php
class Example
{
public function foo()
{
//code
}
public function bar()
{
$this->foo();
}
}
The pseudo-variable $this is available
when a method is called from within an
object context. $this is a reference
to the calling object (usually the
object to which the method belongs,
but possibly another object, if the
method is called statically from the
context of a secondary object).
Used for when you want to work with local variables.
You can also read more about it from here.
function bark() {
print "{$this->Name} says Woof!\n";
}
One time I know I end up using the this equivalent in other languages is to implement a 'Fluent' interface; each class method which would otherwise return void instead returns this, so that method calls can be easily chained together.
public function DoThis(){
//Do stuff here...
return $this;
}
public function DoThat(){
//do other stuff here...
return $this;
}
The above could be called like so:
myObject->DoThis()->DoThat();
Which can be useful for some things.
$this is used when you have created a new instance of an object.
For example, imagine this :
class Test {
private $_hello = "hello";
public function getHello () {
echo $this->_hello; // note that I removed the $ from _hello !
}
public function setHello ($hello) {
$this->_hello = $hello;
}
}
In order to access to the method getHello, I have to create a new instance of the class Test, like this :
$obj = new Test ();
// Then, I can access to the getHello method :
echo $obj->getHello ();
// will output "hello"
$obj->setHello("lala");
echo $obj->getHello ();
// will output "lala"
In fact, $this is used inside the class, when instancied. It is refered as a scope.
Inside your class you use $this (for accessing *$_hello* for example) but outside the class, $this does NOT refer to the elements inside your class (like *$_hello*), it's $obj that does.
Now, the main difference between $obj and $this is since $obj access your class from the outside, some restrictions happens : if you define something private or protected in your class, like my variable *$_hello*, $obj CAN'T access it (it's private!) but $this can, becase $this leave inside the class.
no i think ur idea is wrong.. $this is used when refers to a object of the same class.. like this
think we have a variable value $var and in THAT instance of that object should be set to 5
$this->var=5;
The use $this is to reference methods or instance variables belonging to the current object
$this->name = $name
or
$this->callSomeMethod()
that is going to use the variable or method implemented in the current object subclassed or not.
If you would like to specifically call an implementation of of the parent class you would do something like
parent::callSomeMethod()
Whenever you want to use a variable that is outside of the function but inside the same class, you use $this. $this refers to the current php class that the property or function you are going to access resides in. It is a core php concept.
<?php
class identity {
public $name;
public $age;
public function display() {
return $this->name . 'is'. $this->age . 'years old';
}
}
?>