How construct is working here in my script?
If I am not using function __construct() then my script is giving output using function Cat(). What is the right way to use Construct?
class Cat
{
function Cat1()
{
echo 'wow-wow';
}
function Cat()
{
echo 'meow';
}
function __construct()
{
echo 'meow'."</br>";
echo 'You are reading this because I am in</br>$billi my mind came from class cat which is using</br> function __construct(). That was my origin ';
}
}
$billi= new Cat();
Because in this case, when you have a method Cat, it's a constructor.
PHP recognizes when you have a method which is exactly same the class name as a constructor.
Related
I was trying to figure out if I can instantiate a class within its own constructor and I came across this:
Why Can You Instantiate a Class within its Definition?.
Then I tried the same thing in PHP:
Class someClass {
function __construct() {
$objNew = new someClass();
$objNew->doit();
}
function doit() {
echo "Do it man!\n";
}
}
$oNew = new someClass();
Everytime I tried to run this I got a "Segmentation Fault" error.....
With reference to the above code and even the link posted above, I want to think that instantiating a class within its own constructor would cause an infinite number of objects to get created (until the server crashes, of course!).....any thoughts on what is going on above? Why is it ok to do this in Java and (perhaps) not in PHP?
It's not the same thing. On the question Why Can You Instantiate a Class within its Definition?, a static method is used to instantiate his class. Static methods are stored with the class definition (like a blueprint) inside the heap memory and do not require to be instantiated.
You could create a static method, and this one will have to create a new instance of your class:
Class someClass {
function __construct() {
$this->doit();
}
static function createSomeClass() {
return new someClass();
}
function doit() {
echo "Do it man!\n";
}
}
$oNew = someClass::createSomeClass();
Php is not compiled but interpreted. Java is compiled and after this executed. So the class itself is not yet all defined and you call it again in php so this throws an error.
Below is the right solution for you
<?php
Class someClass {
function __construct() {
$this->doit();
}
function doit() {
echo "Do it man!\n";
}
}
$oNew = new someClass();
?>
If all you want to do is call that method when object is instantiated. Then, there's no meaning of doing this $objNew = new someClass();. Its useless. Simply, do this:
class someClass {
function __construct() {
$this->doit();
}
function doit() {
echo "Do it man!\n";
}
}
$oNew = new someClass();
Is there a way to do something like this:
class Test {
if(!empty($somevariable)) {
public function somefunction() {
}
}
}
I know this might not be best practice, but I need to do this for a very specific problem I have, so is there anyway to do it?
I just want that function to be included in the class if that variable (which is tied to a URL param) is not empty. As it is written now, I get Error: syntax error, unexpected T_VARIABLE, expecting T_FUNCTION
Thanks!
It depends on the your specific use case, and I don't have enough info to give a specific answer, but I can think of one possible fix.
Extend the class, using an if statement. Put everything except the one function in AbstractTest.
<?php
abstract class AbstractTest
{
// Rest of your code in here
}
if (!empty($somevariable)) {
class Test extends AbstractTest {
public function somefunction() {
}
}
} else {
class Test extends AbstractTest { }
}
Now, the class Test only has the method somefunction if $somevariable isn't empty. Otherwise it directly extends AbstractTest and doesn't add the new method.
Call the required function if the variable is not empty.
<?php
class Test {
public function myFunct() {
//Function description
}
}
$oTest = new Test();
if(!empty($_GET['urlParam'])) {
oTest->myFunc();
}
?>
class Test {
public function somefunction() {
}
}
is all you need actually.
Please note that a function inside a class is called 'method'.
AFAIK you cannot have a condition out of the method in class scope (if that flows)
Class Test {
if (empty($Var)){
public function Test_Method (){
}
}
}
Will not work. Why not have it constantly exisisting but only call the method when it's needed?
Example:
Class Test {
public function Some_Method(){
return 23094; // Return something for example purpose
}
}
Then from your PHP:
$Var = ""; // set an empty string
$Class = new Test();
if (empty($Var)){
echo $Class->Some_Method(); // Will output if $Var is empty
}
Perhaps you trying to validate a string within OOP scope, then take this example:
Class New_Test {
public $Variable; // Set a public variable
public function Set(){
$This->Variable = "This is not empty"; // When calling, $this->variable will not be empty
}
public function Fail_Safe(){
return "something"; // return a string
}
}
Then out of Scope:
$Class = new New_Test();
if (empty($Class->Variable)){
$Class->Fail_Safe();
} // Call failsafe if the variable in OOP scope is empty
This question already has answers here:
calling class method (with constructors) without object instantiation in php
(6 answers)
Closed 9 years ago.
I have the class people
ex:
class People{
function name($name){
echo "the name".$name;
}
}
how to make a class calling function automatically without having to call the method :
$var=new People ()
please give me the answer?
Add a constructor function:
function __construct() {
$this->name("My name");
}
This does not make a whole lot of sense though, but it's what you asked for :-)
you can do what you want by using a constructor. In php this is done by declaring a method in the class called __construct(). The constructor is run any time the object is created. so in your example
<?php
class People{
public function __construct($name)
{
name($name);
}
function name($name){
echo "the name".$name;
}
}
$var = new People("dave");
the other thing you may be referring to is statics but you do call a method you just dont instantiate an instance of the class
<?php
class People{
static function name($name){
echo "the name".$name;
}
}
People::name("Dave");
this will output "the nameDave"
Every time you create instance constructor is called you just need to explicitly add it in your class.E.g:
class People{
public function __construct() {
echo 'constructing';
}
function name($name){
echo "the name".$name;
}
}
But before start doing actual stuff, I recommend reading: http://php.net/manual/en/language.oop5.php
Edit: From your comments it seems you want to call method statically. If you want to call a method without instantiating you should mark function as static. In your example:
public static function name($name){
echo "the name".$name;
}
And usage:
Person::name('my name');
You are looking for the Constructor.
class Bla {
public function __construct() { // runs when class is instantiated
}
}
Test this:
class Family {
private $myself;
private $mother = '';
private $father = '';
public function __construct($myname) {
$this->myself = $myname;
}
public function printFamily() {
print_r($this);
}
public function setFather($name) {
$this->father = $name;
}
public function setMother($name) {
$this->mother = $name;
}
}
$fam = new Family('George Walker Bush');
$fam->setFather('George Herbert Walker Bush');
$fam->setMother('Barbara Pierce Bush');
$fam->printFamily();
I want to be able to create methods within __construct
I tried using lambda in the following way
// This is what I am trying to achieve as an end result
class A extends Z{
public function __construct() {
parent::__construct()
}
public function myfunc() { // do something }
}
// This was an attempt to implement it
class A extends Z{
public function __construct() {
//example
if ($something_is_true) {
$this->myfunc = function () {}
}
parent::__construct()
}
}
I hope this explains what I am trying to achieve
EDIT
I have URLs mapped to functions, and I want to have some logic to determine what URL-mapped-functions exist on the class
Don't think that's possible. But another way to dynamically 'create' methods within a class is to use the magic __call() method.
With this method implemented, any attempt to call a non-existent method on an object will call the __call() method instead. The first parameter passed in will be the name of the function that the user called, and the second parameter will be the arguments.
See the manual for further details.
Once a class has been defined, you can't add new methods to it using standard PHP. I'd advise using __call as well but you can also accomplish what you want, if you're ok with using variable variables, by creating the function contents dynamically with create_function:
<?php
class A
{
public function __construct()
{
$this->addUpEchoAndReturn=create_function('$a,$b','$c=$a+$b;echo "$a+$b=$c<hr />";return $c;');
}
public function add_up_and_echo($a,$b,$c,$d)
{
$fn=$this->addUpEchoAndReturn;
return $fn($fn($a, $b),$fn($c, $d));
}
}
$x=new A();
$result=$x->add_up_and_echo(3,4,5,25);
echo "<hr /><hr />Final Result: $result";
?>
Suppose both base and son class have a method method_1,
and there's another method method_2 of base.
inside base::method_2,how can I point $this->method_1 to base::method_1 no matter whether $this is a instance of base or son?
If I understand you correctly, you want something like this:
<?php
class base {
public function method1() {
echo "base:method1\n";
}
public function method2() {
if(get_class($this) == 'base') {
$this->method1();
}
else {
parent::method1();
}
echo "base:method2\n";
}
}
class son extends base {
public function method1() {
echo "son:method1\n";
}
}
$obj = new son();
$obj->method2();
where the call to method2 would always use the base version of the method1.
The best way I could do it is as above, but this code won't work since base has no parent. I'm pretty sure what you're trying to do isn't possible.
This is the error you will get:
PHP Fatal error: Cannot access parent:: when current class scope has no parent in
This will do what you want. Props to dbers for the example code (even if his didn't quite work).
<?php
class base {
public function method1() {
echo "base::method1\n";
}
public function method2() {
if (get_parent_class($this) === FALSE) {
echo get_class($this)." has no parent\n";
$this->method1();
} else {
echo get_class($this)." has parent\n";
call_user_func(array(get_parent_class($this), 'method1'));
}
}
}
class son extends base {
public function method1() {
echo "son::method1\n";
}
}
$b = new base();
$b->method2();
$s = new son();
$s->method2();
?>
Outputs:
base has no parent
base::method1
son has parent
base::method1
Make the function private:
<?php
class A
{
public function __construct()
{
$this->foo();
$this->bar();
}
private function foo() { echo "A::foo()\n"; }
public function bar() { echo "A::bar()\n"; }
}
class B extends A
{
public function foo() { echo "B::foo()\n"; }
public function bar() { echo "B::bar()\n"; }
}
new B();
?>
The output is:
A::foo()
B::bar()
Yes it does. It's singular (one parent).
son->method_1 can add to or override ALL of base->method_1 functionality.
son->method_1 can simply add an additional function, and utilize the rest of the functionality of it's parent's instance of method_1
So calling $this->method_1 would use base->method_1, and son->method_1 as long as what you want to use from base isn't overridden in son.
If you call a method that doesn't exist in your subclass, PHP will traverse the class hierarchy until it finds an ancestor class which implements the function you want. This means that if your son class doesn't implement method_2, PHP will automatically look for the nearest ancestor which does. In your case, it will call method_2 of base as you want.
If you are overriding the method_2 in your son class, and you want to do your own implementation of method_2 and also call the base::method_2 implementation then you can use the parent keyword:
class son extends base {
public function method_2() {
parent::method_2();
//do son::method_2()-specific stuff here
}
}
You can't chain parent calls together, so if base was a subclass of GrandparentClass you couldn't do something like this:
parent::parent::method_2(); // trying to call grandparent::method_2
// but this call will fail
But you can directly refer to ancestor classes by name, so this would work:
GrandparentClass::method_2();
And just to take it a little further, there is also a function called class_parents() which returns an array of every ancestor class your class inherits from. This could help if you wanted to go back, say, two ancestors, but you didn't know its specific name for some reason, you could still call the function using eval().
For example, this code would call GrandparentClass::method_2() without directly referencing the class by name in your code:
$parents = class_parents($this);
eval(end($parents) . "::method_2();");
Hope that helps.