0

I am in this situation: I want that an object do a thing ONLY if it has been called by another object:

EX:

    class obj{

      private $doIt=false;
      private function enableDoIt(){

        $this->doIt=true;

      }

      public function fn(){

        $obj= new obj();
        $obj->enableDoIt(); // must work

      }

    }


    $obj=new obj();
    $obj->enableDoIt(); // <- must fail

I want to enable a setting only from my code and do not let the user of the class to set it, so I can't use public setters...

Any idea?

EDIT:

As I see in your comment, I need something like:

obj friend obj

This way I can use my private vars from inside my class with a new istance of myclass itself.

class obj{

  private $count=0;

  private function fn(){
      nc=new obj();
      nc->cont=2; //called from inside class obj -> want to work
    }  
  }

nc=new obj();
nc->cont=2; //called from outside class obj -> want to not work
Francesco
  • 555
  • 4
  • 23
  • 1
    This is unclear. If that function where you want to access to succeed is a public function in global namespace, then it is usable by anyone. Though it certainly would also fail, since your method `enableDoIt()` is private to the class. So what is your _real_ way to differ between the two attempts? _Maybe_ you are looking for something like the `friend` keyword some OOP languages offer. PHP does _not_ offer such thing. – arkascha Dec 06 '15 at 18:41
  • Your function is already private... no? – plalx Dec 06 '15 at 18:42
  • 1
    http://stackoverflow.com/questions/317835/php-equivalent-of-friend-or-internal and http://techblog.procurios.nl/k/news/view/49401/14863/friend-classes-in-php.html might be of interest for you. – arkascha Dec 06 '15 at 18:45
  • @arkascha I edited the post – Francesco Dec 06 '15 at 19:08
  • Sorry, but that edit does not make sense. You declare the class `myclass` as friend to itself. Also it is unclear where the connection is between class `obj` and class `myclass` you now introduce. – arkascha Dec 06 '15 at 19:11
  • @Francesco just curious, but are you looking for [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern)? – Rajdeep Paul Dec 06 '15 at 19:41
  • @arkascha myclass and obj are just examples... name them as you prefer... what I want is something like what I have explained, what do u not understand? – Francesco Dec 06 '15 at 21:25
  • @RajdeepPaul no I m not looking for singleton... – Francesco Dec 06 '15 at 21:27
  • This is still vague to me. What access should be allowed? If I interpret that example code right, then all access to an objects internal properties should be blocked, except for objects of the same type when attempted from within a method of the object to be modified? _Why?_ – arkascha Dec 07 '15 at 07:58

0 Answers0