access object outside through an abstract function - php

Given the following classes:
<?php
class test{
static public function statfunc()
{
echo "this is the static function<br/>";
$api= new object;
}
}
class traductor
{
public function display()
{
echo "this is the object function";
}
}
test::statfunc();
$api->display();
This does not display the message "this is the static function<br/>".
Is there a way to instantiate through a static function and get that object outside?
Thanks... I am inexperienced regarding object programming code.

You should return the object from your static function:
static public function statfunc()
{
$api = new traductor;
return $api;
}
And then store the returned object in a variable that you can use.
$api = test::statfunc();
$api->display();

Your use of declaration is a bit off. Your code results in 2 fatal errors. First, class object is not found, you should replace:
$api= new object;
With
return new traductor;
Being a static class, they perform an action, they don't hold data, hence the static keyword. Down the line when you start working with $this and etc, remember that. You need to return the result to another variable.
test::statfunc();
$api->display();
Should become:
$api = test::statfunc();
$api->display();
See, http://php.net/manual/en/language.oop5.static.php for some more information on static keywords and examples.

Related

What is the true definition of $this in PHP?

I currently am using PHP and was reading the PHP manual but still have a problem with $this.
Is $this something global or is it is just another variable name to build objects on?
Here is an example:
public function using_a_function($variable1, $variable2, $variable3)
{
$params = array(
'associative1' => $variable1,
'associative2' => $variable2,
'associative3' => $variable3
);
$params['associative4'] = $this->get_function1($params);
return $this->get_function2($params);
}
How would $this work for the return function? I guess I am confused on how this function builds. I understand building the associate array part with a name being a valuekey names => value, but $this throws me off on this example.
$this is only used in object oriented programming (OOP) and refers to the current object.
class SomeObject{
public function returnThis(){
return $this;
}
}
$object = new SomeObject();
var_dump($object === $object->returnThis()); // true
This is used inside the object to reach member variables and methods.
class SomeOtherClass{
private $variable;
public function publicMethod(){
$this->variable;
$this->privateMethod();
}
private function privateMethod(){
//
}
}
It is refered to as the Object scope, lets use an example class.
Class Example
{
private $property;
public function A($foo)
{
$this->property = $foo;
// we are telling the method to look at the object scope not the method scope
}
public function B()
{
return self::property; // self:: is the same as $this
}
}
We can now instance our object and use it in another way also:
$e = new Example;
$e::A('some text');
// would do the same as
$e->A('some other text');
This is just a way of accessing the scope of the Object because methods cannot access other method scopes.
You can also extend a class and use the parent:: to call the class extension scope, for example:
Class Db extends PDO
{
public function __construct()
{
parent::__construct(....
Which would access the PDO construct method rather than its own construct method.
In your case, the method is calling other methods that are in the object. Which can be called using $this-> or self::

PHP OOP - Accessing property value is returning empty

I have the following class, and for some reason it's not accessing the test property. Why is this? I'm new to OOP, so please be easy on me. Thanks
class Test {
private $test;
function __contruct() {
$this->test = "test";
}
static function test() {
echo $this->test;
}
}
$test = new Test;
$test::test();
Because static methods are callable without an instance of the object
created, the pseudo-variable $this is not available inside the method
declared as static.
PHP Documentations.
Good morning.
It seems you have 3 issues with your code.
There is a syntax error at constructor line change it from __contruct to __construct.
Change test function visibility to public
Access your function with the -> instead of ::
To elaborate further on the above answers: Static methods and variables are not linked to any particular instance of the object, this is why you have to call test with $test::test(). This also means that you cannot access an instance variable from without a static method and it doesn't really make sense to do so (If you had multiple instances of the object with different values set for that variable, how would the interpreter know which instance/value to use?)
If you want to have a field accessible from a static method then you have to make the field static as well. So, if you wanted to have $test accessible from your static method test() then you'd have to write your function as something along these lines:
class Test {
private static $test;
function __contruct() {
Test::$test = "test";
}
public function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
However, it doesn't really make sense to be initialising a static field like that in your constructor. So you'd more likely be wanting to do something like:
class Test {
private static $test = "test";
function __contruct() {
}
public static function test() {
echo Test::$test;
}
}
$test = new Test;
$test::test();
Or, if you don't actually require test() to be static then you could just make it an instance method:
class Test {
private $test = "test";
function __contruct() {
$this->$test = "test"
}
public function test() {
echo $this->$test;
}
}
$test = new Test;
$test->test();

what does this mean in PHP ()->

I've seen this use of syntax a few times on the Yii framework. I tried searching for an explanation but got no examples. A link will be nice if possible. It goes something like class::model()->function();
My understanding is that model is an object of class therefore it can access the function. So I tried to code it but I get " Call to a member function sound() on a non-object in". Here's my code
class animal
{
private static $obj;
public static function obj($className = __CLASS__)
{
return self::$obj;
}
public static function walk()
{
return "walking";
}
}
include('animal.php');
class cat extends animal
{
public static function obj($className = __CLASS__)
{
return parent::obj($className);
}
public static function sound()
{
return "meow";
}
}
echo cat::obj()->sound();
Also what benefits does it have?
That is called an object operator and this, ->, calls a class method from your created object which is defined in that class.
Here is an explanation and some examples.
$obj = new Class; // Object of the class
$obj->classMethod(); // Calling a method from that class with the object
echo cat::obj()->sound();
This will display the output of the sound() method, called on the object that is returned from cat::obj().
The reason it's failing for you is because cat::obj() is not returning a valid object.
And the reason for that is because the obj() method returns the static obj property, but you're not actually setting that obj property anywhere.
The pattern you're trying to use here is known as a "Singleton" object. In this pattern, you call an obj() method to get the single instance of the class; every call to the method will give you the same object.
However the first call to the method needs to instantiate the object; this is what you're missing.
public static function obj($className = __CLASS__){
if(!static::$obj) {static::$obj = new static;}
return static::$obj;
}
See the new line where the object is created if it doesn't exist.
Also note that I've changed self to static. The way you're using this with class inheritance means that you probably expect to have a different static object for each class type, self will always return the root animal::$obj property, whereas static will return the $obj property for whichever class you're calling it from.
There are a few other bugs you need to watch out for too. For example, you've defined the sound() method as static, but you're calling it with ->, so it shouldn't be static.
Hope that helps.
The cat::obj() returns you a object of the type cat. With ->sound(); you're executing the function sound() from the class cat. All that should return "meow".
cat::obj() returns an object; ->sound(); execute a method of this object. Equivalent is
$o = cat::obj();
$o->sound();

Accessing a public/private function inside a static function?

Due to the fact that you can not use $this-> inside a static functio, how are you supposed to access regular functions inside a static?
private function hey()
{
return 'hello';
}
public final static function get()
{
return $this->hey();
}
This throws an error, because you can't use $this-> inside a static.
private function hey()
{
return 'hello';
}
public final static function get()
{
return self::hey();
}
This throws the following error:
Non-static method Vote::get() should not be called statically
How can you access regular methods inside a static method? In the same class*
Static methods can only invoke other static methods in a class. If you want to access a non-static member, then the method itself must be non-static.
Alternatively, you could pass in an object instance into the static method and access its members. As the static method is declared in the same class as the static members you're interested in, it should still work because of how visibility works in PHP
class Foo {
private function bar () {
return get_class ($this);
}
static public function baz (Foo $quux) {
return $quux -> bar ();
}
}
Do note though, that just because you can do this, it's questionable whether you should. This kind of code breaks good object-oriented programming practice.
You can either provide a reference to an instance to the static method:
class My {
protected myProtected() {
// do something
}
public myPublic() {
// do something
}
public static myStatic(My $obj) {
$obj->myProtected(); // can access protected/private members
$obj->myPublic();
}
}
$something = new My;
// A static method call:
My::myStatic($something);
// A member function call:
$something->myPublic();
As shown above, static methods can access private and protected members (properties and methods) on objects of the class they are a member of.
Alternatively you can use the singleton pattern (evaluate this option) if you only ever need one instance.
I solved this by creating an object of the concerning class inside a static method. This way i can expose some specific public functions as static function as well. Other public functions can only be used like $object->public_function();
A small code example:
class Person
{
public static function sayHi()
{
return (new Person())->saySomething("hi");
}
public function saySomething($text)
{
echo($text);
}
private function smile()
{
# dome some smile logic
}
}
This way you can only say hi if using the static function but you can also say other things when creating an object like $peter->saySomething('hi');.
Public functions can also use the private functions this way.
Note that i'm not sure if this is best practice but it works in my situation where i want to be able to generate a token without creating an object by hand each time.
I can for example simply issue or verify a token string like TokenManager::getTokenToken(); or TokenManager::verifyToken("TokenHere"); but i can also issue a token object like $manager = new TokenGenerator(); so i can use functionality as $manager->createToken();, $manager->updateToken(updateObjectHere); or $manager->storeToken();

how to make object public to all function in a class?

I've created a class that calls an object in the "__construct" how can i make this object available through out the class.
class SocialMedia { function __construct() { $object = "whatever"; } }
how can I access $object in the other functions (which are static) from with in the class.
I've tried to use "$this->object" but I get an error "$this when not in object context" when I try to call it from my other static functions.
Use
self::$object = 'whatever'
instead and read the PHP Manual on the static keyword
On a sidenote, statics are death to testability, so you might just was well forget what you just learned and use instance variables instead.
Try defining your object inside the scope of the class, right above the function. So, as an example:
class SocialMedia { public $object; function __construct() { $object = "whatever"; } }
Or you could try defining it as "public static" instead of just "public". As an example, this:
class SocialMedia { public static $object; function __construct() { $object = "whatever"; } }
make it static:
class SocialMedia {
protected static $object;
function __construct() {
self::$object = "whatever";
}
}
If $object is not static then you have a problem. You need to be able to refernce a specific instance of the class. Youll need to pass the actual instance of SocialMedia to its static method or come up with some other shenanigans:
public static function someMethod(SocialMedia $instance, $args)
{
// do stuff with $instance->object and $args
}
public function methodThatUsesStaticMethod($args)
{
self::someMethod($this, $args);
}
If $object is static then you can use the scope resolution operator to access it as others have mentioned:
public static $object;
public static function someMethod($args)
{
$object = self::$object;
// do stuff with $object and $args
}
But then you have another issue... What happens if no instance of SocialMedia has been created yet and so SocialMedia::$object is not yet set?
You could make your class a singleton (OOP Patterns in PHP Manual) but that really isn't any better solution if you want testability and/or dependency injection. No matter how you suggarcoat it you are after a global variable and sooner or later you'll find out all the troubles they bring.

Categories