0

Sorry for the weird title wording.

I want a class to have a property that can be viewed but not changed, and I want to set it inside a function.

Like this:

class Foo {
    public int $bar;

    public function __construct(int $input) {
        if ($input < 4) {
            $this->bar = $input;
        }
    }
}

$foo = new Foo(2);
echo $foo->bar; // Returns 2
$foo->bar = 1   // Gives error
RazerMoon
  • 45
  • 4

1 Answers1

-1

Yes, this is possible and a very common practice:

class Foo
{
    private $bar;

    public function getBar()
    {
        return $this->bar;
    }

    public function __construct() {
        // set $bar according to some logic
    }
}
noam
  • 538
  • 5
  • 19
  • Yes, but the getter reveals there is a hidden property. So it is not completely private in that case. – Markus Zeller Jul 24 '20 at 18:42
  • @MarkusZeller If you want to not reveal the property, you can just not provide a getter. The `private` word means that the property cannot be accessed (directly) from outside the class, nothing more. – noam Jul 24 '20 at 18:54
  • This should be added to the answer to clarify that. I made that comment to make clear, the answer is somewhat incomplete because of no explanation ("yes, it is possible" is none) and improving quality. – Markus Zeller Jul 24 '20 at 19:03
  • @MarkusZeller What exactly in the question do you think this makes more clear? I am happy to improve my question if needed, but I am not sure what you mean. – noam Jul 25 '20 at 07:32
  • Read the title. The word constant or private is not mentioned even once in the answer to tell the difference. As I said, your code is correct, but the answer itself is of very low quality. – Markus Zeller Jul 25 '20 at 11:04
  • @MarkusZeller, thank you for your feedback. You can suggest another answer, and you can suggest an edit to my answer. – noam Jul 25 '20 at 11:17
  • Changing your answer is also no good practice on this platform. That is intended for minor mistakes like formatting or typos. It looks like you are not very familiar on how a good answer should look like. As your answer is already accepted, since the code did help OP, and all important info is given in the comments, I won't write an extra answer to bloat this topic. – Markus Zeller Jul 25 '20 at 11:25