Geril
Geril

Reputation: 159

Set default variables in class

I got here this code:

class Article {
    public $content,$author, $all;

    public function __construct() {
        $this->all = "{$this->author} Wrote: {$this->content}";
    }
}
$newArt = new Article();
$newArt->content = "Lorem ipsum";

This is working fine but my question is: Isn't there any way to set that values automatically in setting new class? Something like:

$newArt = new Article("content of content variable", "author");

Upvotes: 0

Views: 76

Answers (3)

visigoth
visigoth

Reputation: 208

It's bad practice to set your class members public. Only class methods (functions) should be public, and even then some may be protected and/or private.

By convention, set your class members private or protected, then access them through setters and getters, and have a construct function with your required properties to instantiate your article objects:

class Article{
   private $content;
   private $author;
   private $all;

   public function __construct($content, $author){
      $this->content = $content;
      $this->author = $author;
      $this->all = "{$this->author} wrote: {$this->content}";
   }

   public function getAll{
      return $this->all;
   }
}

Then, you can call this class in your client script:

$article = new Article('Lorem Ipsum', 'William Shakespear');
echo $article->getAll();

Upvotes: 1

user3593520
user3593520

Reputation: 141

slight modifcation to @AbraCadaver (not enough rep to add comment yet)

public function __construct($content='my default content', $author='my default author') {
    $this->content = $content;
    $this->author = $author;
    $this->all = "{$this->author} Wrote: {$this->content}";
}

I'm suggesting this because it looks like the OP doesn't require parameters on construction. This way it can be instantiated without passing anything and if nothing is passed it defaults to some predefined values.

another approach would be:

public function __construct() {
    $this->content = 'my default content';
    $this->author = 'my default author';
    $this->all = "{$this->author} Wrote: {$this->content}";
}

and then use functions like this to set the values later:

public set_author ($author) {
   $this->author = $author;
}

I prefer keeping variables private and then building set and get public functions myself. It leaves room for validation and formatting rules to be added later.

Upvotes: 2

AbraCadaver
AbraCadaver

Reputation: 78994

Yes:

public function __construct($content, $author) {
    $this->content = $content;
    $this->author = $author;
    $this->all = "{$this->author} Wrote: {$this->content}";
}

Other ways depending on the goal, but how does $this->content and $this->author get set in your existing code?

Upvotes: 3

Related Questions