Reputation: 429
I have asked this question beforehand, but I might have worded it poorly. I did not get the answer.
I have an Image
class that always creates an instance of an Id
class when it constructs. Each Image always has an Id
, and when Image
is destroyed, the Id
is destroyed as well. As far as I understand, this is called Object Composition.
My Image class (here: $myImage), during intialization/construction, creates a property: $this->id = new Id(); I want $this->id to be able to access a property of $myImage. Simple example:
class Image {
public $fileSize;
public $id;
const validMimeTypes = array('image/png', 'image/jpeg');
public function __construct($fileSize = 0.0) {
$this->fileSize = $fileSize;
$this->id = new Id();
}
}
class Id {
public function echoMe() {
echo $creatorInstance->fileSize;
echo creatorClass::validMimeTypes;
//This is what I'd like to know how to do
}
}
$myImage = new Image();
$myImage->id->echoMe();
I would like to know how an Id
can access one of its creator's properties.
I would like to know if there are differences between accessing class constants and object properties if it turns out to not be obvious.
For example, Id
might need the creator object's fileName
and fileSize
to generate a hash, or it might need its validMimeTypes
, which could be a const array describing that class.
I don't mind knowing if this is has better alternatives - in fact, I'm curious - but first of all I'd like to know how to achieve this without passing down arguments during the __construct() stage.
Upvotes: 0
Views: 289
Reputation: 15131
First, you shouldn't use public attributes, because it breaks encapsulation.
Take a look at the code below. You can pass $this
to the target class, and be able to access its methods and attributes:
class A
{
public function __construct()
{
$this->b = new B($this);
}
public function func()
{
echo "hello, world!";
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
echo $a->func();
}
}
$a = new A;
It will display hello, world!
So, in your case, just use $this->id = new Id($this);
and create a constructor to Id
class that will set the Image instance to a class attribute.
Upvotes: 2