How do you declare a class property as an object?
I tried:
public $objectname = new $Object();
But it didn't work. Additionally, why should you do it like that?
Isn't it better to just instantiate that object and just use its members?
From the PHP manual on class properties (emphasis mine):
Class member variables are called "properties". You may also see them referred to using other terms such as "attributes" or "fields", but for the purposes of this reference we will use "properties". They are defined by using one of the keywords public, protected, or private, followed by a normal variable declaration. This declaration may include an initialization, but this initialization must be a constant value --that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.
Either create it inside the constructor (composition)
class Foo
{
protected $bar;
public function __construct()
{
$this->bar = new Bar;
}
}
or inject it in the constructor (aggregation)
class Foo
{
protected $bar;
public function __construct(Bar $bar)
{
$this->bar = $bar;
}
}
or use setter injection.
class Foo
{
protected $bar;
public function setBar(Bar $bar)
{
$this->bar = $bar
}
}
You want to favor aggregation over composition.
If you are just looking to instantiate to a generic class you can do:
$objectname = new stdClass;
I don't believe you can do this in the declaration of a property so you'd have to just declare $objectname and in the constructor set it to new stdClass.
You can create a new class in constructer area then set it as new object.
class CampaignGroupsProperty
{
public $id;
public $name;
}
class GetCampaignGroupsResponse
{
public $result;
public $resultCode;
public $campaignGroups;
public function __construct()
{
$this->campaignGroups = new CampaignGroupsProperty();
}
}
Then you can call it like
$response = new GetCampaignGroupsResponse();
$response->campaignGroups->id = 'whatever';
$response->result=true;
PHP doesn't support explicit typing of class members. So you can't say:
public Object $objectname;
If the class Object exists, and you want an instance of it, try:
public $objectname = new Object();
Related
$model = new static($variable);
All these are within a method inside a class, I am trying to technically understand what this piece of code does. I ran around in the Google world. But can't find anything that leads me to an answer. Is this just another way of saying.
$model = new static $variable;
Also what about this
$model = new static;
Does this mean I'm initializing a variable and settings it's value to null but I am just persisting the variable not to lose the value after running the method?
static in this case means the current object scope. It is used in late static binding.
Normally this is going to be the same as using self. The place it differs is when you have a object heirarchy where the reference to the scope is defined on a parent but is being called on the child. self in that case would reference the parents scope whereas static would reference the child's
class A{
function selfFactory(){
return new self();
}
function staticFactory(){
return new static();
}
}
class B extends A{
}
$b = new B();
$a1 = $b->selfFactory(); // a1 is an instance of A
$a2 = $b->staticFactory(); // a2 is an instance of B
It's easiest to think about self as being the defining scope and static being the current object scope.
self is simply a "shortcut name" for the class it occurs in. static is its newer late static binding cousin, which always refers to the current class. I.e. when extending a class, static can also refer to the child class if called from the child context.
new static just means make new instance of the current class and is simply the more dynamic cousin of new self.
And yeah, static == more dynamic is weird.
You have to put it in the context of a class where static is a reference to the class it is called in. We can optionally pass $variable as a parameter to the __construct function of the instance you are creating.
Like so:
class myClass {
private $variable1;
public function __construct($variable2) {
$this->variable1 = $variable2;
}
public static function instantiator() {
$variable3 = 'some parameter';
$model = new static($variable3); // <-this where it happens.
return $model;
}
}
Here static refers to myClass and we pass the variable 'some parameter' as a parameter to the __construct function.
You can use new static() to instantiate a group of class objects from within the class, and have it work with extensions to the class as well.
class myClass {
$some_value = 'foo';
public function __construct($id) {
if($this->validId($id)) {
$this->load($id);
}
}
protected function validId($id) {
// check if id is valid.
return true; // or false, depending
}
protected function load($id) {
// do a db query and populate the object's properties
}
public static function getBy($property, $value) {
// 1st check to see if $property is a valid property
// if yes, then query the db for all objects that match
$matching_objects = array();
foreach($matching as $id) {
$matching_objects[] = new static($id); // calls the constructor from the class it is called from, which is useful for inheritance.
}
return $matching_objects;
}
}
myChildClass extends myClass {
$some_value = 'bar'; //
}
$child_collection = myChildClass::getBy('color','red'); // gets all red ones
$child_object = $child_collection[0];
print_r($child_object); // you'll see it's an object of myChildClass
The keyword new is used to make an object of already defined class
$model = new static($variable);
so here there is an object of model created which is an instance of class static
Is it possible to get the value of an overridden NON static member variable of a parent class?
I understand that to get the value of a STATIC member variable you use self::$var1 or ClassName::$var1, but how do you get the value of a NON static member variable?
For instance...
class One
{
public $var1 = 'old var';
}
class Two extends One
{
public $var1 = 'new var';
public function getOldVar()
{
//somehow get old var
}
}
Thanks so much in advance!
Nope. Once you've overridden a non-static property value it's gone. You can't use the parent:: syntax with non-static properties like you can with methods.
However, using the static keyword you can utilize PHP's late static binding capabilities to access a static parent property because the static values are bound to the class in which they're assigned:
class Top
{
public static $prop = 'Parent';
}
class Child extends Top {
public static $prop = 'Child';
public static function getParentProp() {
return parent::$prop;
}
public static function getProp() {
return static::$prop;
}
}
echo Child::getParentProp(); // outputs "Parent"
echo Child::getProp(); // outputs "Child"
Note that you cannot override a non-static property with a static one in a child class to achieve what you're attempting because PHP (and all other scripting languages, I believe) uses the same table to store property names. This is just a limitation of the language.
You can do this using reflection:
class One {
public $var1 = 'old var';
}
class Two extends One {
public $var1 = 'new var';
public function getOldVar() {
$ref = new ReflectionClass(get_parent_class());
$props = $ref->getDefaultProperties();
return $props['var1'];
}
}
$two = new Two;
var_dump($two->getOldVar()); // string(7) "old var"
Here's some working code:
class A {
public $Foo;
public function GetFoo() {
$this->Foo = 'Bar';
}
}
class B extends A {
function __construct() {
$this->GetFoo();
echo $this->Foo;
}
}
$b = new B(); // Outputs "Bar"
Is there any way I can make this "prettier" (i.e. without the A::GetFoo() method)? I would've thought that wrapping the population of the $this->Foo inside a A::__construct() would work, but it doesn't.
Just to wrap it up, here's what I want: class A instantiates my DB object and that object is usable for every child class of A.
Perhaps you're overriding the parent's constructor without calling in from B?
class A {
protected $Foo = null;
public function __construct() {
$this->Foo = 'Bar';
}
}
class B extends A {
public function __construct() {
parent::__construct();
echo $this->Foo;
}
}
From the PHP manual:
"Class properties must be defined as
public, private, or protected. If
declared using var without an explicit
visibility keyword, the property will
be defined as public."
So, your class B can see $this->Foo. You don't have to call GetFoo() first. You must, however, call the parent constructor first if you need to reference $this->Foo inside of your constructor for class B.
I'm a little confused about this paragraph on OO visibilty in PHP. was curious if someone could explain it to me. examples would be GREAT! my brain is not thinking clear.
http://www.php.net/manual/en/language.oop5.visibility.php
The first paragraph reads
The visibility of a property or method
can be defined by prefixing the
declaration with the keywords public,
protected or private. Class members
declared public can be accessed
everywhere. Members declared protected
can be accessed only within the class
itself and by inherited and parent
classes. Members declared as private
may only be accessed by the class that
defines the member.
how can a parent class access a childs class member?
That's how:
class A {
public function test() {
$b = new B;
echo $b->foo;
}
}
class B extends A {
protected $foo = 'bar';
}
$a = new A;
$a->test();
PHP is an interpreted language. Properties are resolved at runtime, not at the compiling stage. And access modifiers are just checked when a property is accessed.
It makes no difference if you ad-hoc inject a new (undeclared) property so it becomes public, or if you declare a protected property in an inherited class.
The private really only affects the accessibility from the outside. The ->name resolving at runtime works regardless of that. And the PHP runtime simply doesn't prope if the property declaration was made for the current object instances class. (Unlike for private declarations.)
public scope: property (method, variable etc) can be accessed from any class in any file.
class Example {
public $foo;
}
$example = new Example;
$example->foo = 3; // everything OK
private scope: property can only be accessed only by same class.
class Example {
private $foo;
}
class Child_Class extends Example {
public function some_method()
{
parent::foo = 3; // raises error
}
}
protected scope: property can only be accessed by same class or by other classes that extend it.
class Example {
protected $foo;
}
class Child_Class extends Example {
public function some_method()
{
parent::foo = 3; // this is OK
}
}
It all has to do with a technique named encapsulation, in which you must not allow a class member's state or behavior to be changed outside the class. http://en.wikipedia.org/wiki/Encapsulation_(object-oriented_programming)
Protected is a type of visibility which makes properties and methods declared protected available in the child classes of the declared class.
class Parent {
public $name = 'MyName';
protected $age = 20;
private $school = 'MySchool';
}
class Child extends Parent {
public function __construct() {
echo $this -> name; // valid as public
echo $this -> age; // valid as protected
echo $this -> school; // invalid as private
}
}
There you understand protected is something that used in inheritance.
I've recently been working on some class files and I've noticed that the member variables had been set in a protected static mode like protected static $_someVar and accessed like static::$_someVar.
I understand the concept of visibility and that having something set as protected static will ensure the member variable can only be accessed in the super class or derived classes but can I access protected static variables only in static methods?
Thanks
If I understand correctly, what you are referring to is called late-static bindings. If you have this:
class A {
protected static $_foo = 'bar';
protected static function test() {
echo self::$_foo;
}
}
class B extends A {
protected static $_foo = 'baz';
}
B::test(); // outputs 'bar'
If you change the self bit to:
echo static::$_foo;
Then do:
B::test(); // outputs 'baz'
Because self refers to the class where $_foo was defined (A), while static references the class that called it at runtime (B).
And of course, yes you can access static protected members outside a static method (i.e.: object context), although visibility and scope still matters.
Static variables exist on the class, rather than on instances of the class. You can access them from non-static methods, invoking them something like:
self::$_someVar
The reason this works is that self is a reference to the current class, rather than to the current instance (like $this).
By way of demonstration:
<?
class A {
protected static $foo = "bar";
public function bar() {
echo self::$foo;
}
}
class B extends A { }
$a = new A();
$a->bar();
$b = new B();
$b->bar();
?>
Output is barbar. However, if you try to access it directly:
echo A::$foo;
Then PHP will properly complain at you for trying to access a protected member.