Jump to content

Recommended Posts

Aside from setting a default value, is there any reason a class needs properties or a property with no default value?

 

Here are two examples I am working with. One has a default car color from a property that gets changed (overwritten?), the other just sets the color with no property.

 

Property with default color value

<?php
class Car {
  public $color = 'red';
}

$bmw = new Car ();
echo $bmw -> color; // red

$bmw -> color = 'blue';
echo "<br>";
echo $bmw -> color; // blue

Class with no property sets color

<?php
class Car {
}

$bmw = new Car ();
$bmw -> color = 'blue';
echo $bmw -> color; // blue
Link to comment
https://forums.phpfreaks.com/topic/303059-oop-class-properties/
Share on other sites

You should define properties, with or without defaults. Putting them in the class helps to document what the properties are, and personally I give defaults (even just 0 or empty strings) to be clear what type of values it will have.

 

I mean, look at Car:

class Car {
  public $color = 'red';
}
class Car {
  public $color;
}
class Car {
}
The first has an obvious property, and the default may or may not make sense but at least you get a feel for it. (In this example I don't think having "red" makes sense.) The second has an obvious property but it's not clear whether it might have a string, int, or object as its value. (Docblocks are good for that too.) The third is completely unhelpful.
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.