I'm a totally newbie in class writing in PHP, started a couple days ago.
I'd like to declare a new "public property" inside a method to be used in other methods.
This is what I thought (Of course it doesnt' work!):
class hello {
public function b() {
public $c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $c;
}
}
$new = new hello;
$new->output();
Thanks in advance for any tips.
I'd like to declare a new "public property" inside a method to be used in other methods.
If the other methods are part of the same class, you don't need a public property, a private property will fit your needs. Private properties are accessible within the same class only which helps to keep things simple.
Also understand the difference between declaring a property and assigning a value to it. Declaring is done when the code is loaded, assigning when it executes. So declaring (or defining) a property (private or public) needs a special place in the PHP syntax, that is in the body of your class and not inside in a function.
You access properties inside the class by using the special variable $this in PHP.
The pseudo-variable $this is available when a method is called from within an object context. $this is a reference to the calling object (usually the object to which the method belongs [to]). From PHP Manual
Private property example:
class hello {
private $c; # properties defined like this have the value NULL by default
public function b() {
$this->c = 20; # assign the value 20 to private property $c
}
public function output() {
echo $this->c; # access private property $c
}
}
$new = new hello;
$new->output(); # NULL
$new->b();
$new->output(); # 20
Hope this is helpful. You use a private property because everything else in your program does not need to care about it, so inside your class you know that nothing else can manipulate the value. See as well VisibilityDocs.
Every variable of the class is public when you define it inside of a method (function)! You can do this the following way:
class hello {
public function b() {
$this->c = 20;
}
public function output() {
echo $this->c;
}
}
$new = new hello;
$new->output();
or let function b() return $c and then pass it as a variable to output():
class hello {
public function b() {
return $c = 20;
}
public function output($c) {
echo $c;
}
}
$new = new hello;
$c = $new->b();
$new->output($c);
Remember all variables inside a function are ONLY accessable from within that particular function...unless you use $this of course, which makes the variable a class property!
Also, it's recommended to only return variables...echo is only for the real output, the pure HTML, the template, your view, if you know what I mean :)
Try this instead:
class hello {
public $c = null;
public function b() {
$this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $this->c;
}
}
class hello {
public $c;
public function b() {
$this->c = 20;
}
public function output() {
$this->c;
}
}
Note: If you need to use a property in another method you don't need to declare that method as public, you should declare the property as private, and you'll have access to your property with no problem:
class hello {
private $c;
public function b() {
$this->c = 20;
}
public function output() {
$this->c;
}
}
class hello {
public $c;
public function b() {
$this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
return $this->c;
}
}
$new = new hello;
echo $new->output();
class hello {
var $c;
function __construct() { // __construct is called when creating a new instance
$this->c = 20;
}
public function getC() {
return $this->c;
// beter to return a value this way you can later decide what to do with the value without modifying the class
}
}
$new = new hello; // create new instance and thus call __construct().
echo $new->getC(); // echo the value
Rewrite this code like this :-
class hello {
public $c;
public function b() {
public $this->c = 20; //I'd like to make $c usable by the method output()
}
public function output() {
echo $this->c;
}
}
$new = new hello;
$new->output();
Related
I want $foo->display(); to display Hello World
Here is what I tried:
class MyAttribute
{
public function init($var)
{
$this->setString($var);
}
public function display()
{
$this->setString = $var;
}
}
$foo = new MyAttribute("Hello World");
$foo->display();
You need to use the return keyword to pass the variable back, however that is not your issue, consider the following:
class MyAttribute {
private $attr;
public function __construct($attr)
{
$this->attr = $attr;
}
public function get_attr()
{
return $this->attr;
}
}
$attr = new MyAttribute('Hello World');
echo $attr->get_attr();
The constructor executes first when the class is instantiated and we set the property $attr with the variable that is passed to said constructor.
In the get_attr functionm the important part to notice is the return keyword which I have linked you to the documentation for it above.
You don't necessarily need a constructor, you can add another function called set_attr which sets/changes the value of $attr but seeing as you are using the constructor in your original code, I've left it in.
Live Example
Repl
Reading Material
PHP OOP
You Can use __construct because PHP will automatically call the __construct() method/function when you create an object from your class.
we can provide a value for the $par property when we create our MyAttribute objects.
class MyAttribute
{
private $var;
public function __construct($var)
{
$this->var = $var;
}
public function display()
{
return $this->var;
}
}
$foo = new MyAttribute("Hello World");
echo $foo->display();
I'm trying to change a property in my parent class with my child class but I'm not getting the result I'm expecting.
I've done some research (like Change parent variable from child class), but I can't seem to find the problem.
class A {
public $msg;
public function __construct() {
$this->msg = 'foo';
}
public function setMessage($string) {
$this->msg = $string;
}
public function getMessage() {
var_dump($this->msg); // For demo purposes
}
public function triggerB() {
$b = new B;
}
}
class B extends A {
public function __construct() {
parent::setMessage('bar');
}
}
$a = new A;
$a->getMessage();
$a->triggerB();
$a->getMessage();
The output I get is "foo" twice and I expect it to be "foo" "bar".
Could anyone explain me what i'm doing wrong and how I can fix this?
In my actual code I want the child-class to validate some $_POST values, and return the outcome to the Main-class. The parent uses the child to validate.
You are having your object A and creating an instance of it and storing it in the variable $a, in the global scope. And then you are creating another instance of your class B and storing it in a variable $b which is in the scope of the method triggerB().
You can only change the properties of the parent class A if you pass an argument to your another class B.
So something like this should suffice:
<?php declare(strict_types = 1);
class A {
public $msg;
public function __construct() {
$this->msg = 'foo';
}
public function setMessage(string $string) {
$this->msg = $string;
}
public function getMessage() {
var_dump($this->msg); // For demo purposes
}
public function triggerB() {
(new B($this));
}
}
class B {
public function __construct(A $a) {
$a->msg = "bar";
}
}
$a = new A;
$a->getMessage();
$a->triggerB();
$a->getMessage();
This approach is better suited to readability and better dependency management.
Another approach:
<?php declare(strict_types = 1);
class A {
public $msg;
public function __construct() {
$this->msg = 'foo';
}
public function setMessage(string $string) {
$this->msg = $string;
}
public function getMessage() {
var_dump($this->msg); // For demo purposes
}
public function triggerB() {
$this->msg = 'bar';
}
}
class B {
public function __construct(A $a) {
$a->msg = "bar";
}
}
$a = new A;
$a->getMessage();
$a->triggerB();
$a->getMessage();
This is performance wise better, but if you are going to be doing something complex, the first method is better.
Note: The above code is for PHP7.
Your triggerB() method does not actually do anything:
public function triggerB() {
$b = new B;
}
You are creating a new object and assign that to the $b variable. As soon as the method finishes, the $b variable / object ceases to exist.
Also note that the $b variable in your method is is no way related to the $a variable in the global scope so setting any of its properties has no influence on $a.
I'm new to programming. I have this going on:
I have Class A, which have many functions. One of those functions is functionX.
In functionX I need to make a call to functionY which belongs to another class: Class B.
So how do I acces to functionY from inside functionX?
I use Codeigniter.
Thanks in advance.
Try and experiment with this.
class ClassA {
public function functionX() {
$classB = new ClassB();
echo $classB->functionY();
}
}
class ClassB {
public function functionY() {
return "Stahp, no more OO, stahp!";
}
}
Class function? A static method?
If you have an instance (public) method, you just call $classB->functionY().
If you have a static method, you would call ClassB::functionY();
So:
class ClassA {
public function functionX(){
$classB = new ClassB();
// echo 'foo';
echo $classB->functionY();
// echo 'bar';
echo ClassB::functionYStatic();
}
}
class ClassB {
public $someVar;
public static $someVar2 = 'bar';
function __construct(){
$this->someVar = 'foo';
}
public function functionY(){
return $this->someVar;
}
public static function functionYStatic(){
return self::$someVar2;
}
}
Well that depends. If that function is a static function or not.
First off you must include the file with the class...
include_once('file_with_myclass.php');
If it is static you can call it like this:
ClassName::myFunction()
If it is not, then you create an instance of the class and then call the function on that instance.
$obj = new ClassName();
$obj->myFunction();
As you can guess the function being static means you can call it without the need of creating an instance. That is useful for example if you have a class Math and want to define a function that takes to arguments to calculate the sum of them. It wouldn't really be useful to create an instance of Math to do that, so you can declare as static and use it that way.
Here's a link to the docs with further info
http://www.php.net/manual/en/keyword.class.php
If functionY is static you can call ClassB::functionY(). Else you must create instance of Class B first. Like:
$instance = ClassB;
$instance->functionY();
But maybe you mean something else?
Looks like one of your class has a dependency to another one:
<?php
class A
{
public function x()
{
echo 'hello world';
}
}
class B
{
private $a;
public function __construct(A $a)
{
$this->a = $a;
}
public function y()
{
$this->a->x();
}
}
$a = new A();
$b = new B($a);
$b->y();
Depending how your code looks like, if it makes sense, you can inject class A into y()
public function y(A $a)
{
// your code with $a
}
I'd like do do this:
class A {
public static $var = 'foo';
}
class B {
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
echo $this->a::$var; // <---- ERROR
echo get_class($this->a)::$var; // <---- ERROR
// WORKING but awful
$a = $this->a;
echo $a::$var;
}
}
$b = new B(new A());
$b->f();
Note that I don't know if $a is an instance of A or another class, I just know that it has a static $var member. So, unfortunately, I can't use A::$var inside f.
Does anyone know if there is a single-expression syntax to do this, using PHP 5.3+?
You're passing an instance of A into B, but $var is a static Member of A which can only be accessed using :: like A::$var.
private function f() {
echo A::$var;
}
EDIT:
if you want to make it dependant of the instance stored in $a you could do something like:
public function f() {
$class = get_class($this->a);
echo $class::$var;
}
First thing I'm seeing is that you couldn't call f() as it is private.
$b->f();
Then maybe you can turn to something like this?
class B extends A{
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
echo static::$var;
}
}
The following will work but I'd question why you'd want to do this:
class A {
public static $var = 'foo';
}
class B {
private $a;
public function __construct($a) {
$this->a = $a;
}
public function f() {
if ($this->a instanceof A) {
echo A::$var;
}
}
}
$b = new B(new A());
$b->f();
you don't need to do anything specifically with $this->a as $var is static to the class.
You could write a function like so:
function get_static_property($class, $property) {
return $class::$$property;
}
I can't help but wonder why you would need this. Any reason why you can't have A implement an interface? Or use a trait?
That way you can just echo $this->a->someMethodName().
PS. returning strings is generally preferred over echoing inside methods.
I have a global variable outside my class = $MyNumber;
How do I declare this as a property in myClass?
For every method in my class, this is what I do:
class myClass() {
private function foo() {
$privateNumber = $GLOBALS['MyNumber'];
}
}
I want this
class myClass() {
//What goes here?
var $classNumber = ???//the global $MyNumber;
private function foo() {
$privateNumber = $this->classNumber;
}
}
EDIT: I want to create a variable based on the global $MyNumber but
modified before using it in the methods
something like: var $classNumber = global $MyNumber + 100;
You probably don't really want to be doing this, as it's going to be a nightmare to debug, but it seems to be possible. The key is the part where you assign by reference in the constructor.
$GLOBALS = array(
'MyNumber' => 1
);
class Foo {
protected $glob;
public function __construct() {
global $GLOBALS;
$this->glob =& $GLOBALS;
}
public function getGlob() {
return $this->glob['MyNumber'];
}
}
$f = new Foo;
echo $f->getGlob() . "\n";
$GLOBALS['MyNumber'] = 2;
echo $f->getGlob() . "\n";
The output will be
1
2
which indicates that it's being assigned by reference, not value.
As I said, it will be a nightmare to debug, so you really shouldn't do this. Have a read through the wikipedia article on encapsulation; basically, your object should ideally manage its own data and the methods in which that data is modified; even public properties are generally, IMHO, a bad idea.
Try to avoid globals, instead you can use something like this
class myClass() {
private $myNumber;
public function setNumber($number) {
$this->myNumber = $number;
}
}
Now you can call
$class = new myClass();
$class->setNumber('1234');
Simply use the global keyword.
e.g.:
class myClass() {
private function foo() {
global $MyNumber;
...
$MyNumber will then become accessible (and indeed modifyable) within that method.
However, the use of globals is often frowned upon (they can give off a bad code smell), so you might want to consider using a singleton class to store anything of this nature. (Then again, without knowing more about what you're trying to achieve this might be a very bad idea - a define could well be more useful.)
What I've experienced is that you can't assign your global variable to a class variable directly.
class myClass() {
public $var = $GLOBALS['variable'];
public function func() {
var_dump($this->var);
}
}
With the code right above, you get an error saying "Parse error: syntax error, unexpected '$GLOBALS'"
But if we do something like this,
class myClass() {
public $var = array();
public function __construct() {
$this->var = $GLOBALS['variable'];
}
public function func() {
var_dump($this->var);
}
}
Our code will work fine.
Where we assign a global variable to a class variable must be inside a function. And I've used constructor function for this.
So, you can access your global variable inside the every function of a class just using $this->var;
What about using constructor?
class myClass {
$myNumber = NULL;
public function __construct() {
global myNumber;
$this->myNumber = &myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
Or much better this way (passing the global variable as parameter when inicializin the object - read only)
class myClass {
$myNumber = NULL;
public function __construct($myNumber) {
$this->myNumber = $myNumber;
}
public function foo() {
echo $this->myNumber;
}
}
$instance = new myClass($myNumber);
If you want to access a property from inside a class you should:
private $classNumber = 8;
I found that globals can be used as follows:
Create new class:
class globalObj{
public function glob(){
global $MyNumber;
return $this;
}
}
So, now the global is an object and can be used in the same way:
$this->glob();
class myClass
{
protected $foo;
public function __construct(&$var)
{
$this->foo = &$var;
}
public function foo()
{
return ++$this->foo;
}
}