0

I am working on a PHP class which looks like this:

<?php
    class xyz{
           public $car1;
           public $car2;
           private $owner;

            public function __construct ($type){
              $this->car1 = $type;
              $this->owner = "John";
              return $this->owner();
          }
            private function owner(){
             return "Owner of ".$this->car1." is ".$this->owner;
          }

Now, here's the problem when I call this class via other code, I can easily access private variable and the return function is not working correctly.

Here's the sample:

  <?php
    $car = new xyz("Sedan");
    echo $car; //Expected result: Owner of Sedan is John.
   ?>

If I print $car, Here's what I get

 Object ( [car1] => Sedan [car2] => "" [owner:xyz:private] => John )

How can I achieve my desired results and How can I protect private variable?

All the helps and suggestions will be appreciated.

Thanks!

8
  • 6
    You can't return from a constructor. Just echo $car->owner() or possibly use __toString() Commented Jan 8, 2018 at 19:34
  • 1
    You cannot echo a Class, you should have a function inside of it. Commented Jan 8, 2018 at 19:34
  • 1
    @Phiter you can echo a class, but you need __toString magic method defined. Commented Jan 8, 2018 at 19:36
  • Oh that's good to know, thank you! Commented Jan 8, 2018 at 19:36
  • protect private variable from what? Commented Jan 8, 2018 at 19:38

1 Answer 1

3
  1. Constructors are not supposed to return any value. The class constructor is supposed to initialize an object when creating a new instance (e.g. when you write $car = new xyz("sedan");, so anything you return goes nowhere. Create other methods in the class to return values.
  2. If you want to echo the owner, make the owner method public and do `echo $car->owner();". The method returns a string, and then the string is echoed. Simple.
  3. Echoing the object directly should result in an error in php 7, maybe you are running an older version of php that returns what you've seen, which is what happens if you call var_dump($car);. If you want to control how an object is converted into a string, you need to override the __toString method (see the php documentation).
  4. Properties and methods visibility keywords are working fine, if you try to use $car->owner or $car->owner() without changing visibility you should see errors.
Sign up to request clarification or add additional context in comments.

3 Comments

@ 3, I'm using print_r, not echo. But __toString works!
Any suggestions how to protect private data from getting access outside the class?
Private data is not getting accessed outside class, it's OOP basics.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.